【问题标题】:Swift - Attribute string background color on next lineSwift - 下一行的属性字符串背景颜色
【发布时间】:2020-02-12 22:29:43
【问题描述】:

我有一个标签,我希望在第 1 行显示一些单词,在第 2 行显示一些单词。我可以通过在字符串之间放置“\n”来实现它。第 2 行的单词是带有背景颜色的属性字符串,但是背景颜色从第一行开始。

有没有办法,我可以在第 2 行获得背景颜色?

下面是代码:

let attributedString = NSMutableAttributedString(string: "Line 1 Text" ?? "")
let attributesForNonSelectedRow = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold),NSAttributedString.Key.foregroundColor:UIColor(rgb: 0x707070),NSAttributedString.Key.backgroundColor:UIColor(rgb: 0xE5E5E5)]
let myTitle = NSAttributedString(string: " \n Line 2 Text", attributes: attributesForNonSelectedRow)
attributedString.append(myTitle)
searchTitleLabel.lineBreakMode = .byWordWrapping
searchTitleLabel.numberOfLines = 0
searchTitleLabel.attributedText = attributedString

【问题讨论】:

    标签: ios swift string nsattributedstring


    【解决方案1】:

    简单的解决方案: - 只需在第一行字符串中添加 /n - 即可解决问题

    let attributedString = NSMutableAttributedString(string: "Line 1 Text\n" ?? "")
    let attributesForNonSelectedRow = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold),NSAttributedString.Key.foregroundColor:UIColor(rgb: 0x707070),NSAttributedString.Key.backgroundColor:UIColor(rgb: 0xE5E5E5)]
    let myTitle = NSAttributedString(string: "Line 2 Text", attributes: attributesForNonSelectedRow)
    attributedString.append(myTitle)
    searchTitleLabel.lineBreakMode = .byWordWrapping
    searchTitleLabel.numberOfLines = 0
    searchTitleLabel.attributedText = attributedString
    

    通过约束解决:

    你为什么不尝试通过提供Leading,Top和Height约束来设置标签的约束,你可以实现它..

    【讨论】:

      【解决方案2】:

      我写了这个问题。我所要做的就是将“\n”放在第 1 行的后面而不是第 2 行的前面,这样就解决了背景颜色问题。

      let attributedString = NSMutableAttributedString(string: "Line 1 Text \n" ?? "")
      let attributesForNonSelectedRow = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold),NSAttributedString.Key.foregroundColor:UIColor(rgb: 0x707070),NSAttributedString.Key.backgroundColor:UIColor(rgb: 0xE5E5E5)]
      let myTitle = NSAttributedString(string: "Line 2 Text", attributes: attributesForNonSelectedRow)
      attributedString.append(myTitle)
      searchTitleLabel.lineBreakMode = .byWordWrapping
      searchTitleLabel.numberOfLines = 0
      searchTitleLabel.attributedText = attributedString
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-28
        • 1970-01-01
        • 1970-01-01
        • 2015-07-07
        • 2015-04-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多