NSMutableAttributedString在更改字体时崩溃?
我确定mutable意味着它可以改变,所以为什么会发生这种情况?NSMutableAttributedString在更改字体时崩溃?
attrString = [[NSMutableAttributedString alloc] initWithString:@"Tip 1: Aisle Management The most obvious step – although one that still has not been taken by a disconcerting number of organisations – is to configure cabinets in hot and cold aisles. If you haven’t got your racks into cold and hot aisle configurations, we can advise ways in which you can achieve improved airflow performance."];
[attrString setFont:[UIFont systemFontOfSize:20] range:NSMakeRange(0, 23)];
[attrString setFont:[UIFont systemFontOfSize:15] range:NSMakeRange(24, 325)];
[attrString setTextColor:[UIColor blackColor] range:NSMakeRange(0,184)];
[attrString setTextColor:[UIColor blueColor] range:NSMakeRange(185,325)];
break;
我的catextlayer和我的nsmutableattributedsring都是在我的头文件中定义的。我对上面的开关改变我的字符串,然后把这个代码更新catextlayer字符串显示在:
//updates catext layer
TextLayer = [CATextLayer layer];
TextLayer.bounds = CGRectMake(0.0f, 0.0f, 245.0f, 290.0f);
TextLayer.string = attrString;
TextLayer.position = CGPointMake(162.0, 250.0f);
TextLayer.wrapped = YES;
[self.view.layer addSublayer:TextLayer];
它崩溃时,它试图设置字体,但我不能明白为什么?
- [NSConcreteMutableAttributedString setfont程序:范围:]:无法识别的选择发送到实例0xd384420 *终止应用程序由于未捕获的异常 'NSInvalidArgumentException',原因:“ - [NSConcreteMutableAttributedString setfont程序:范围:]:无法识别的选择发送例如0xd384420'
这是怎么发生的?
NSMutableAttributedString没有setFont:range:function。
从这里拍摄.... iphone/ipad: How exactly use NSAttributedString?
所以我做了一些从文档阅读。
的功能是...
[NSMutableAttirbutedString setAttributes:NSDictionary range:NSRange];
所以,你应该能够做这样的事......
[string setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Helvetice-Neue"]} range:NSMakeRange(0, 2)];
或
[string setAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Helvetice-Neue"], NSFontAttributeName", nil] range:NSMakeRange(0, 2)];
如果你还在使用旧的ObjC语法。
希望有所帮助。
我得到使用未申报NSFontAttributeName的错误?我还没有尝试过颜色。 – dev6546
阅读文档后进行编辑。 https://developer.apple.com/library/mac//#/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/Reference/Reference.html – Fogmeister
我认为这些文档只适用于os x 10+,这也会导致崩溃。 – dev6546
首先,attrString是你说的一个属性吗?如果它是一个属性,你最好检查一下你是否声明了属性的copy属性,你估计是使用编译器生成的setter?如果YES编译器生成的setter将复制消息发送给对象以进行复制。复制消息将生成不可变的副本。也就是说,它创建一个NSAttributedString,而不是一个NSMutableAttributedString。解决这个问题
的一种方法是,如果你使用ARC编写自己的二传手使用mutableCopy,像这样:
- (void)setTextCopy:(NSMutableAttributedString *)text {
textCopy = [text mutableCopy];
}
或类似这样的,如果你使用手工引用计数:
- (void)setTextCopy:(NSMutableAttributedString *)text {
[textCopy release];
textCopy = [text mutableCopy];
}
另一个解决方法是让textCopy成为NSAttributedString而不是NSMutableAttributedString,并让其余的代码作为一个不可变对象工作。
参考: 1️⃣How to copy a NSMutableAttributedString 2️⃣NSConcreteAttributedString mutableString crash
下面是一些免费代码,演示如何使用归因字符串:github.com/artmayes167/Attribute – AMayes