gpt4 book ai didi

cocoa (雪豹)NSTextView的textStorage -setAttributes :range: removes characters!

转载 作者:行者123 更新时间:2023-12-03 16:29:52 25 4
gpt4 key购买 nike

我不确定我做错了什么。我有一个 NSTextView 并注册为其 textStorage 属性的委托(delegate)。当我收到 -textStorageDidProcessEditing:notification: 时,我尝试将属性应用于文本中的字符范围。它确实对角色做了“一些事情”,但不是我所期望的......他们只是消失了!

经过严格精炼的代码示例。这应该确保文本字段中的第二个字符始终为红色:

-(void)textStorageDidProcessEditing:(NSNotification *)notification {
NSTextStorage *textStorage = [textView textStorage];
if ([[textStorage string] length] > 1) {
NSColor *color = [NSColor redColor];
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:color, NSForegroundColorAttributeName, nil];
[textStorage setAttributes:attributes range:NSMakeRange(1, 1)];
}
}

相反,当我输入序列“abcdefg”时,我得到“a”,然后当我点击“b”时,似乎没有任何反应,然后当我点击“cdefg”时,打字会正常发生,使最终结果为“acdefg”。 ..“b”丢失了!

如果我开始按退格键,我必须按退格键 7 次,就好像“b”实际上在那里,但只是没有被绘制(光标在删除“b”时停止,然后在下一个退格键上删除“a”正如预期的那样)。

如果我在绘制 View 之前使用相同的 -setAttributes:range: 方法将属性应用于 View 中的某些默认文本,那么它会完全按照我的预期进行。

有什么线索吗?这似乎是 NSTextStorageDelegate 的正常使用:)

我尝试在文本字段上调用 ​​-setNeedsDisplay 但无济于事。

最佳答案

想通了。使用 NSTextStorage 的 -addAttribute:value:range 有效。我仍然不完全明白为什么,但至少我可以克服它并继续前进。

-(void)textStorageDidProcessEditing:(NSNotification *)notification {
// ... SNIP ...
[textStorage addAttribute:NSForegroundColorAttributeName
value:[NSColor redColor]
range:NSMakeRange(1, 1)];
}

也使代码不再那么困惑。

关于 cocoa (雪豹)NSTextView的textStorage -setAttributes :range: removes characters!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3992214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com