NSMutableAttributedString - NSForegroundColorAttributeName

BDG*_*pps 2 iphone objective-c ios4 ios ios5

我试图设置我的数组中的所有范围的颜色,但我收到此错误.我不明白为什么.范围都是有效的.我甚至尝试手动插入一个范围来测试它.谢谢.

CGContextSetFillColorWithColor:无效的上下文0x0

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:tv.text];

for (NSString * s in array) {
        [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSRangeFromString(s)];
}

CATextLayer *textlayer = [[CATextLayer alloc]init];
textlayer.frame = CGRectMake(0, 0, 320, 480);
[self.view.layer addSublayer:textlayer];
textlayer.string = @"aString"; //works
textlayer.string = string; //does not work
tv.text = @"";
Run Code Online (Sandbox Code Playgroud)

Mat*_*man 9

代码示例是否与您尝试构建的代码完全相同?我非常肯定NSForegroundColorAttributeName只能在Mac OS X SDK和iOS 6.0及更高版本中使用,因此示例代码甚至不应该编译.

你想要的可能是kCTForegroundColorAttributeName通过一个CGColorRef而不是一个NSColor.

[string addAttribute:(id)kCTForegroundColorAttributeName
               value:(id)[UIColor redColor].CGColor
               range:NSRangeFromString(s)];
Run Code Online (Sandbox Code Playgroud)

但我不确定这是否真的是无效上下文错误的原因.

  • 仅供参考,`NSForegroundColorAttributeName`从iOS 6.0开始可用,所以没有人会感到困惑. (2认同)