【问题标题】:Swift iOS. Multi line UILabel background color to follow the text斯威夫特 iOS。多行 UILabel 背景颜色跟随文本
【发布时间】:2016-10-30 07:26:11
【问题描述】:

我有一个多行 UILabel,我想将其背景颜色设置为与使用鼠标突出显示 Web 浏览器上的文本时完全相同但似乎找不到解决方案。

这是我在故事板中得到的:

这就是我的目标:

这是我上面提到的浏览器示例:

【问题讨论】:

    标签: ios swift uilabel background-color


    【解决方案1】:

    是的,使用属性文本。快来这里

    let textBgColor = UIColor.greenColor()
    let attributes = [
            NSBackgroundColorAttributeName : textBgColor
    ]
    let attributedString = NSAttributedString(string: Constant.kDescriptionArray[0], attributes: attributes)
    
    descriptionLabel.attributedText = attributedString
    

    【讨论】:

      【解决方案2】:

      尝试使用属性字符串

      NSMutableAttributedString *string = [[NSMutableAttributedString alloc]
                                         initWithString:@"Some text line Some text line\nSome text line"];
      [string addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, string.length)];
      titleLabel.attributedText = string;
      

      编辑: Eric 需要帮助来编写快速代码。我刚刚发布了我拥有的代码,任何具有简单 Swift 知识的人都应该能够编写 Swift 代码:)。毕竟都是关于学习的:)

      但是这里的任何方式都是快速代码。

          let string = NSMutableAttributedString(string: "blah blah", attributes: [NSBackgroundColorAttributeName: UIColor.redColor()])
          label.attributedText = string
      

      【讨论】:

      • 您的答案可能是正确的,但该问题专门要求提供 Swift 代码示例,而不是 Objective-C。请编辑。谢谢!
      猜你喜欢
      • 2016-06-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-23
      • 2017-07-21
      相关资源
      最近更新 更多