如何更改 CFAttributedString 的字符串而不是属性?
How to change CFAttributedString's string but not attributes?
现在我有一个CFAttributedString,整个字符串的属性并不相同,例如索引0-2是蓝色,3-5是黑色,我想改变它的文本,但是没有' t alter the attributes, 我想复制字符串,但我总是不知道什么时候属性开始不同,CFAttributedStringGetAttributes只能指定一个位置获取属性,有没有在字符串中分别复制属性的好方法?或者我可以只更改字符串而不更改属性吗?
你没有解释为什么我们必须在 CFAttributedString 世界中这样做,我当然想不出这样做的理由,所以这里有一个关于如何在 NSAttributedString 世界中这样做的基本概述。基本上,您只需循环遍历第一个字符串的属性并将它们分配给第二个字符串:
// index 0-2 are blue and 3-5 are black
let s = NSMutableAttributedString(string: "blublack", attributes: [
NSForegroundColorAttributeName : UIColor.blackColor()
])
s.addAttributes(
[NSForegroundColorAttributeName : UIColor.blueColor()],
range: NSMakeRange(0,3)
)
// I want to change the text of it,
// but don't alter the attributes
let s2 = NSMutableAttributedString(string: "12345678")
s.enumerateAttributesInRange(NSMakeRange(0,s.length), options: nil, usingBlock: {
d,r,_ in
s2.addAttributes(d, range: r)
})
这给出了预期的结果。当然,如果字符串的长度不同,您还必须问自己该怎么办,但是您没有在问题中提供任何规范,因此处理该问题留作 reader 的练习.
现在我有一个CFAttributedString,整个字符串的属性并不相同,例如索引0-2是蓝色,3-5是黑色,我想改变它的文本,但是没有' t alter the attributes, 我想复制字符串,但我总是不知道什么时候属性开始不同,CFAttributedStringGetAttributes只能指定一个位置获取属性,有没有在字符串中分别复制属性的好方法?或者我可以只更改字符串而不更改属性吗?
你没有解释为什么我们必须在 CFAttributedString 世界中这样做,我当然想不出这样做的理由,所以这里有一个关于如何在 NSAttributedString 世界中这样做的基本概述。基本上,您只需循环遍历第一个字符串的属性并将它们分配给第二个字符串:
// index 0-2 are blue and 3-5 are black
let s = NSMutableAttributedString(string: "blublack", attributes: [
NSForegroundColorAttributeName : UIColor.blackColor()
])
s.addAttributes(
[NSForegroundColorAttributeName : UIColor.blueColor()],
range: NSMakeRange(0,3)
)
// I want to change the text of it,
// but don't alter the attributes
let s2 = NSMutableAttributedString(string: "12345678")
s.enumerateAttributesInRange(NSMakeRange(0,s.length), options: nil, usingBlock: {
d,r,_ in
s2.addAttributes(d, range: r)
})
这给出了预期的结果。当然,如果字符串的长度不同,您还必须问自己该怎么办,但是您没有在问题中提供任何规范,因此处理该问题留作 reader 的练习.