Cannot get foreground color of NSTextView

85 views Asked by At

I am trying to use the code that follows to get the foreground color of an NSTextView. Unfortunately I get a runtime error that must be related with the involved color spaces. How can I fix m

if let textStorage = textView.textStorage {
    let rowObj = textStorage.paragraphs[row]
    let range = NSMakeRange(0, rowObj.string.characters.count)
    colorOrRowBeforeSelection = rowObj.foregroundColor!                
    if(rowObj.foregroundColor != nil) {
        let r = rowObj.foregroundColor!.redComponent
        let g = rowObj.foregroundColor!.greenComponent
        let b = rowObj.foregroundColor!.blueComponent
    } else {
        Log.e("cannot get foreground color components")
    }
} else {
    Log.e("textStorage = nil")
}    

I get the following runtime error:

[General] *** invalid number of components for colorspace in initWithColorSpace:components:count:

1

There are 1 answers

0
Nisba On

I made it working with the following:

let components = UnsafeMutablePointer<CGFloat>.allocate(capacity: 4)
rowObj.foregroundColor!.getComponents(components)
let c = NSColor(colorSpace: NSColorSpace.sRGB, components: components, count: 4)
components.deinitialize()
components.deallocate(capacity: 4)
let r = c.redComponent
let g = c.greenComponent
let b = c.blueComponent

EDIT: I made a fix on the memory handling, now the code works except from the fact the it turns what should be white (in the grey color space) into yellow... hope someone can fix that.