I have text in my editable NSTextView
. In that, i added a color box (NSColorWell
), to change the color of my text. Now i want to get the current color of text that is being edited. In my textDidChange:(from
NSTextViewDelegate`) to change the color i currently have:
NSColor *currentColor = [self.doc.textStorage attribute:NSForegroundColorAttributeName atIndex:(self.doc.selectedRange.location) effectiveRange:nil];
[self.colorBox setColor:currentColor];
colorBox
is the NSColorWell
, and doc
is the NSTextView
. I use the same code to get current font, replacing NSForegroundColorAttributeName
with NSFontAttributeName
. I always get some exceptions in my NSLog
area, most of it i can't understand, but I'll add it anyway:
2015-02-09 20:35:30.413 MPO Word[851:303] Exception detected while handling key input.
2015-02-09 20:35:30.414 MPO Word[851:303] *** -[NSConcreteTextStorage attribute:atIndex:effectiveRange:]: Range or index out of bounds
2015-02-09 20:35:30.418 MPO Word[851:303] (
0 CoreFoundation 0x00007fff8913ef56 __exceptionPreprocess + 198
1 libobjc.A.dylib 0x00007fff8dc18d5e objc_exception_throw + 43
2 CoreFoundation 0x00007fff8913ed8a +[NSException raise:format:arguments:] + 106
3 CoreFoundation 0x00007fff8913ed14 +[NSException raise:format:] + 116
4 AppKit 0x00007fff8597d777 -[NSConcreteTextStorage attribute:atIndex:effectiveRange:] + 130
5 MPO Word 0x0000000100001541 -[MPODocument textDidChange:] + 625
6 Foundation 0x00007fff8c8c5d0e __-[NSNotificationCenter addObserver:selector:name:object:]_block_invoke_1 + 47
7 CoreFoundation 0x00007fff890e77ba _CFXNotificationPost + 2634
8 Foundation 0x00007fff8c8b1fc3 -[NSNotificationCenter postNotificationName:object:userInfo:] + 65
9 AppKit 0x00007fff85e360c6 -[NSTextView(NSSharing) didChangeText] + 348
10 AppKit 0x00007fff85e0221f -[NSTextView insertText:replacementRange:] + 2029
11 AppKit 0x00007fff85c5d104 -[NSKeyBindingManager(NSKeyBindingManager_MultiClients) flushTextForClient:] + 187
12 AppKit 0x00007fff85fb3413 -[NSTextInputContext handleEvent:] + 848
13 AppKit 0x00007fff85e7cfcc -[NSView interpretKeyEvents:] + 248
14 AppKit 0x00007fff85df5bf9 -[NSTextView keyDown:] + 691
15 AppKit 0x00007fff858d30fc -[NSWindow sendEvent:] + 7430
16 AppKit 0x00007fff8586c3a5 -[NSApplication sendEvent:] + 5593
17 AppKit 0x00007fff85802a0e -[NSApplication run] + 555
18 AppKit 0x00007fff85a7eeac NSApplicationMain + 867
19 MPO Word 0x0000000100001092 main + 34
20 MPO Word 0x0000000100001064 start + 52
21 ??? 0x0000000000000003 0x0 + 3
)
Also, the color well clicks, stays in the pressed state until clicked again, where all color goes away. How can i get the color without these kinds of errors ?
My guess would be that effectiveRange can't be null.
Try something like