Now I have a CFAttributedString, and the attribute is not identical in the whole string, for example, index 0-2 are blue and 3-5 are black, I want to change the text of it, but don't alter the attributes, I want to copy the string, but I don't always know when the attributes start being different, CFAttributedStringGetAttributes can only specify one location to get the attributes, is there any good method to copy the attributes respectively in the string? or can I just change the string but not attributes?
You have not explained why we have to do this in the CFAttributedString world, and I certainly can't think of a reason to do so, so here's a basic outline of how to do it in the NSAttributedString world. Basically, you just cycle through the attributes of the first string and assign them to the second string:
// 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)
})
That gives the desired result. Of course you also have to ask yourself what to do if the strings are of different lengths, but you didn't provide any spec for that in your question, so dealing with that issue is left as an exercise for the reader.