gpt4 book ai didi

Cocoa Text - 即时刷新文本

转载 作者:行者123 更新时间:2023-12-03 16:17:40 28 4
gpt4 key购买 nike

在我正在开发的应用程序中,用户输入纯文本,应用程序通过将其转换为 NSAttributedString 来重新格式化文本,并显示它。这一切都发生在现场。

目前,我正在 NSTextView 的 textDidChange 委托(delegate)方法上执行以下操作:

- (void)textDidChange:(NSNotification *)notification {

// saving the cursor position
NSInteger insertionPoint = [[[self.mainTextView selectedRanges] objectAtIndex:0] rangeValue].location;

// this grabs the text view's contact as plain text
[self updateContentFromTextView];

// this creates an attributed strings and displays it
[self updateTextViewFromContent];

// resetting the cursor position
self.mainTextView.selectedRange = NSMakeRange(insertionPoint, 0);
}

虽然这大部分有效,但并不理想。文本似乎会闪烁一瞬间(您尤其会注意到拼写错误下的红点),并且当光标之前靠近可见矩形的边缘之一时,滚动位置会重置。就我而言,这是一个非常不受欢迎的副作用。

所以我的问题是:有没有更好的方法来做我想做的事情?

最佳答案

我认为您对NSTextView如何有一个轻微的误解。作品。用户永远不会输入“纯字符串”,即 NSTextView 的数据存储。 总是 NSTextStorage对象,它是 NSMutableAttributedString 的子类.

您需要做的是向用户正在编辑的现有属性字符串添加/删除属性,而不是替换整个字符串。

您也不应该对 ‑textDidChange: 中的字符串进行更改委托(delegate)方法,因为从该方法更改字符串可能会导致另一个更改通知。

相反,您应该实现委托(delegate)方法 ‑textStorageDidProcessEditing: 。每当文本更改时都会调用此函数。然后您可以像这样修改字符串:

- (void)textStorageDidProcessEditing:(NSNotification*)notification
{
//get the text storage object from the notification
NSTextStorage* textStorage = [notification object];

//get the range of the entire run of text
NSRange aRange = NSMakeRange(0, [textStorage length]);

//for example purposes, change all the text to yellow

//remove existing coloring
[textStorage removeAttribute:NSForegroundColorAttributeName range:aRange];

//add new coloring
[textStorage addAttribute:NSForegroundColorAttributeName
value:[NSColor yellowColor]
range:aRange];
}

关于Cocoa Text - 即时刷新文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6476106/

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