【问题标题】:Why doesn't this properly color the substring in my UILabel?为什么这不能正确地为我的 UILabel 中的子字符串着色?
【发布时间】:2013-10-22 22:42:58
【问题描述】:

我希望一个特定的子字符串是黄色的。我不想将它分解为多个 UILabel,因为这会使布局本地化成为一场噩梦。所以我这样做:

    NSMutableAttributedString* instructions = [[[NSMutableAttributedString alloc] initWithString:self.o_instructionsLabel.text] autorelease];
    NSRange range = [instructions.string rangeOfString:@"FOOBARBAZ"];
    if (range.length > 0)
    {
        [instructions addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:range];
        self.o_instructionsLabel.attributedText = instructions;
    }

但是,标签中的整个文本仍然是白色的。这似乎是所有示例的做法,我验证了范围是正确的,当我转储 instructions 对象时,我看到属性内联,我猜它们应该是。

我做错了什么?

【问题讨论】:

  • 第一个想法是,虽然我猜这不可能,但您使用了自定义 UILabel 类,并且在 (void)drawTextInRect:(CGRect)rect 方法中添加了自定义代码,因此它忽略了属性内容跨度>
  • 您的代码看起来没问题,刚刚在示例项目上进行了测试,它运行良好。这段代码在什么时候执行?
  • 仔细观察,你是正确的使徒。

标签: ios objective-c uikit nsattributedstring


【解决方案1】:

解决方案是drawTextInRect: 中的自定义代码忽略了属性字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-26
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 2015-06-27
    • 2021-12-05
    相关资源
    最近更新 更多