我的可编辑NSTextView
中有文字。在那里,我添加了一个颜色框(NSColorWell
),以更改我的文本的颜色。现在我想获得正在编辑的文本的当前颜色。在我的textDidChange:(from
NSTextViewDelegate`)中更改我当前拥有的颜色:
NSColor *currentColor = [self.doc.textStorage attribute:NSForegroundColorAttributeName atIndex:(self.doc.selectedRange.location) effectiveRange:nil];
[self.colorBox setColor:currentColor];
colorBox
是NSColorWell
,doc
是NSTextView
。我使用相同的代码获取当前字体,将NSForegroundColorAttributeName
替换为NSFontAttributeName
。我总是在我的NSLog
区域中遇到一些例外情况,其中大部分是我无法理解的,但无论如何我都会添加它:
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
)
此外,颜色很好地点击,保持按下状态,直到再次点击,所有颜色消失。如何在没有这些错误的情况下获得颜色?
答案 0 :(得分:0)
我的猜测是,有效范围不能为空。
尝试类似
的内容NSRange effectiveRange = NSMakeRange(0, 1);
NSColor *currentColor = [self.doc.textStorage attribute:NSForegroundColorAttributeName atIndex:(self.doc.selectedRange.location) effectiveRange:&effectiveRange];