【问题标题】:Break UILabel into 2 lines with separate background?将 UILabel 分成两行,背景分开?
【发布时间】:2015-12-11 14:38:30
【问题描述】:

http://imgur.com/yVkhHon.jpg

我希望我的文字成行但有单独的背景。我如何使用 UILabel 实现这一点?

我尝试了填充等,但如果我为标签选择背景颜色,它只会显示单个红色框。

对如何获得与图像相同的效果有任何帮助吗?

【问题讨论】:

    标签: ios objective-c iphone ios7


    【解决方案1】:

    使用以下代码:

    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:self.yourLabel.text];
    
    //EDITED
    [text addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, text.length/2)];
    [text addAttribute:NSBackgroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(text.length/2, text.length/2)];
    
    [self.yourLabel setAttributedText: text];
    

    【讨论】:

    • 嗨,我试过你的代码,它说点地址 NSString 到 NSAttributedString 不兼容
    • 它在启动时崩溃
    • 嗨,谢谢它的工作原理:) 但不是我要找的...如果行分成 2,我想要两种不同的背景颜色。文本的颜色没有不同。知道我必须尝试什么吗??
    • @user1859651 使用我现在编辑的NSBackgroundColorAttributeName。此外,您将需要实现一个逻辑来查找每行中有多少个字符,然后修改颜色属性的range
    • 谢谢.. 会进一步调查。但我一直在寻找有助于提供单独背景的逻辑
    【解决方案2】:

    使用NSAttributesString。创建一个UILabel,创建一个NSAttributesString。然后不要使用标签的setText,而是使用您之前创建的字符串对象调用setAttributedText

    更多关于Apple Documentation的帮助

    【讨论】:

      【解决方案3】:
      [mutableAttributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:selectedRange];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多