简体   繁体   English

如何将CATextLayer与NSMutableAttributedString一起使用

[英]How to use CATextLayer together with NSMutableAttributedString

I try to use a CATextLayer together with a NSMutableAttributedString . 我尝试将CATextLayerNSMutableAttributedString一起使用。

Once I set the string property of my CATextLayer to an NSMutableAttributedString it gets automatically replaced by an immutable NSAttributedString. 将CATextLayer的string属性设置为NSMutableAttributedString后,它将自动被不可变的NSAttributedString替换。

I checked for the result of calling class on the string property before and after setting it and the pointer. 在设置字符串和指针之前和之后,我检查了在字符串属性上调用的结果。 I hand an NSConcreteMutableAttributedString to the CoreTextLayer and right after the setter is called and I ask the CATextLayer for the class of its string property, I get this result: NSConcreteAttributedString . 我将NSConcreteMutableAttributedString传递给CoreTextLayer,并在调用设置方法后立即向CATextLayer询问其string属性的类,得到以下结果: NSConcreteAttributedString Also the pointers are different before and after (obviously). 同样,指针前后(显然)是不同的。

What can I do to get that right? 我该怎么做才能做到这一点?

There's nothing wrong with what's happening, so there's nothing to "get right". 发生的事情没有什么错,因此没有什么要“正确”。 Just look at the documentation! 只需查看文档! The string property is declared like this: string属性的声明如下:

@property(copy) id string

That means exactly what you're seeing: when you set it, it takes an immutable copy. 那正好意味着您所看到的:设置时,它将获得一个不变的副本。 This is deliberate: if it were not so, then the string could be mutated behind the layer's back, which would throw everything off. 这是故意的:如果不是这样,则字符串可能会在图层的背面后面发生突变,这会使所有内容丢掉。 Indeed, if your own classes have any string properties, they should work the same way. 实际上,如果您自己的类具有任何字符串属性,则它们应该以相同的方式工作。

If you need to change the string, just set the string property again. 如果需要更改字符串,只需再次设置string属性。 If you need to change the string based on its current value, fetch the string , make a mutableCopy , change it, and set it - just as with any of the immutable / mutable class cluster pairs in Foundation. 如果您需要根据字符串的当前值更改字符串,请获取string ,创建mutableCopy ,对其进行更改并进行设置-就像Foundation中的任何不可变/可变类簇对一样。

The name of the class is irrelevant, as I presume you realize: it's a class cluster, so private names like NSConcreteMutableAttributedString (instead of NSMutableString) are none of your business. 正如我想您所意识到的那样,类的名称无关紧要:它是一个类集群,因此像NSConcreteMutableAttributedString(而不是NSMutableString)这样的私有名称与您无关。 You should never use the class name as a way of testing whether a mutable Foundation class instance is mutable, in any case: just ask the object whether it responds to a mutable method. 在任何情况下,都决不要使用类名作为测试可变的Foundation类实例是否可变的方法:仅询问对象它是否对可变方法作出响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM