Objective C - NSAttributedString 扩展属性? [英] Objective C - NSAttributedString extend Attributes?

查看:39
本文介绍了Objective C - NSAttributedString 扩展属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户输入我的文本文件时,我希望新字符继承以前的属性.

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.

更多信息

// 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?

推荐答案

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

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];

这篇关于Objective C - NSAttributedString 扩展属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆