Objective C - NSAttributedString 扩展属性?

发布于 2024-11-26 05:24:48 字数 773 浏览 2 评论 0原文

当用户在我的文本字段中输入内容时,我希望新字符继承以前的属性。

我目前从前一个角色获取属性并将其添加为新范围的新属性?我怎样才能让它扩展之前的 attributeString 呢?

// What I have
"a"{attribute1 (0,1)} "b"{attribute2 (1,1)} "c"{attribute3(2,1)}
// What I'm trying to do
"abc" {attribute1 (0,3)}

注意:这对于用户键入的每个字符都必须发生,因此当用户键入时,新字符应该继承以前的属性。

编辑: 更多信息

// So I create a new AttributedString, added it to my mutable string
NSAttributedString *newString = [[NSAttributedString alloc] initWithString:USER_INPUT attributes:self.defaultAttributes];
[_mutableAttributedString insertAttributedString:newString atIndex:selectedNSRange.location];

// Is it possible to add the USER_INPUT to the end of my mutable attributedString and extends the range of the previous attribute?

As the user types into my textfiled I want the new characters to inherit the previous attributes.

I currently get the attributes from the previous character and add it as new attribute for the new range? How can I make it so that it extends the previous attributedString instead?

// What I have
"a"{attribute1 (0,1)} "b"{attribute2 (1,1)} "c"{attribute3(2,1)}
// What I'm trying to do
"abc" {attribute1 (0,3)}

Note: This has to happen for every character that the user types, so as the user type the new character should inherit the previous attributes.

EDIT:
More info

// So I create a new AttributedString, added it to my mutable string
NSAttributedString *newString = [[NSAttributedString alloc] initWithString:USER_INPUT attributes:self.defaultAttributes];
[_mutableAttributedString insertAttributedString:newString atIndex:selectedNSRange.location];

// Is it possible to add the USER_INPUT to the end of my mutable attributedString and extends the range of the previous attribute?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

奈何桥上唱咆哮 2024-12-03 05:24:48

您可以使用 replaceCharactersInRange:withString: 方法来执行此操作。如果指定范围的长度为0,则不会替换任何字符。字符串将被自动赋予其前面的字符的属性,除非它位于开头,在这种情况下,它将被赋予其后面的字符的属性。

NSRange range = NSRangeMake([_mutableAttributedString length],0);
[_mutableAttributedString replaceCharactersInRange:range withString:USER_INPUT];

You can use the replaceCharactersInRange:withString: method to do this. If the length of the specified range is 0, no characters will be replaced. The string will be automatically given the attributes of the character before it, unless it is at the beginning, in which case it will be given the attributes of the character after it.

NSRange range = NSRangeMake([_mutableAttributedString length],0);
[_mutableAttributedString replaceCharactersInRange:range withString:USER_INPUT];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文