删除使用 NSMutableAttributedString 的 UILabel 空白区域的彩色背景

Remove the colored background of empty spaces of a UILabel that uses NSMutableAttributedString

我想知道是否可以在使用 NSMutableAttributedStringUILabel 上删除 space 中设置的彩色背景 "beginning" 每行,当对齐设置为 right 时。

观察:当对齐设置为 left

时一切正常

这是我所期望的:


附加问题: 是否可以在没有颜色的行之间留下一个space?

将标签的 backgroundColor 设置为白色或透明颜色,并将背景颜色应用到 NSMutableAttributedString,如下所示,

//In Swift
let mutableAttributedString = NSMutableAttributedString() //Initialize your string here
mutableAttributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.yellow, range: NSMakeRange(0, mutableAttributedString.length))

//In Objective C
NSMutableAttributedString *mutableAttributedString; //Initialize your string here
[mutableAttributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(0, mutableAttributedString.length)];

如果您使用的是故事板,请更改属性字符串的背景颜色,如附图所示。

刚刚意识到上述解决方案适用于以下情况,

  1. 左对齐最多两行
  2. 右对齐和居中对齐最多一行

请按照此 获得完整的解决方案。

所以我确实花了 45 分钟才找到解决这个问题的方法。我一直在使用我自己的 UILabel 扩展来突出显示文本,但不幸的是,当 textAlignment 设置为正确时,它会突出显示空格或缩进空间,就像你的这个问题。

我意识到除了使用这个 pod,我找不到任何其他解决方案:TTTAttributedLabel https://github.com/TTTAttributedLabel/TTTAttributedLabel

这可以很好地处理 UILabel 的属性字符串设置。虽然 pod 是用 Objective-C 编写的,因此您需要一个桥接头。我想您已经知道如何将 Objective-C 代码移植到您的 Swift 项目中。

override func viewDidLoad() {
    super.viewDidLoad()

    self.view.backgroundColor = .gray

    let label = TTTAttributedLabel(frame: .zero)
    label.textAlignment = .right
    label.numberOfLines = 0


    let attr: [NSAttributedString.Key: Any] = [
        .font: UIFont.boldSystemFont(ofSize: 16.0),
        .foregroundColor: UIColor.black,
        .backgroundColor: UIColor.green
    ]

    label.text = NSAttributedString(string: "How can I Remove\nthe space at the\nbeginning?", attributes: attr)

    self.view.addSubview(label)
    label.translatesAutoresizingMaskIntoConstraints = false

    self.view.addConstraint(NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1.0, constant: 300))
    self.view.addConstraint(NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1.0, constant: 0))

}

结果:

希望对您有所帮助!