objective-c - NSMutableAttributedString 在更改字体时崩溃?

标签 objective-c ios nsattributedstring nsmutablestring

我确定 mutable 意味着它可以更改,那么为什么会这样呢?

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;

我的 cattextlayer 和 nsmutableattributedsring 都在我的头文件中定义。我在一个开关中对上面的字符串进行了更改,然后调用此代码来更新 cattextlayer,该字符串显示在:

//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:range:]: unrecognized selector sent to instance 0xd384420 * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSConcreteMutableAttributedString setFont:range:]: unrecognized selector sent to instance 0xd384420'

为什么会这样?

最佳答案

NSMutableAttributedString 没有 setFont:range: 函数。

取自此处.... 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 语法。

希望对您有所帮助。

关于objective-c - NSMutableAttributedString 在更改字体时崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12517553/

相关文章:

objective-c - 如何正确处理排队 nsoperation 的释放委托(delegate)

iOS:Objective-C:由于 ipad 时间显示 12 小时/24 小时导致的输出问题

fonts - 如何使用 Swift 制作属性字符串?

ios - 使用 NSURLSession 将 NSString 作为 post 方法的主体发送

objective-c - 如何获得对当前 UINavigationController 的引用?

ios - 与启动图像完全一样的启动屏幕

ios - NSAttributedString 错误。它附加了属性字典的描述

ios - 在 UILabel 中为 NSLinkAttributeName 自定义颜色

objective-c - 为什么不调用 didRegisterForRemoteNotificationsWithDeviceToken

ios - 具有自定义 HitTest 的 UIWebView 子类