【问题标题】:Remove the colored background of empty spaces of a UILabel that uses NSMutableAttributedString删除使用 NSMutableAttributedString 的 UILabel 空白区域的彩色背景
【发布时间】:2018-11-08 11:07:59
【问题描述】:

我想知道是否有可能,在使用 NSMutableAttributedStringUILabel 上,在设置对齐时删除在每行“开头”的空白处设置的彩色背景

Obs.:当对齐设置为 left

时一切正常

这是我所期望的:


补充问题: 是否可以在没有颜色的线条之间留出空间?

【问题讨论】:

  • 我无法想象你想要什么,如果你没有及时得到一些答案,你介意上传一个非常精确的输出吗?
  • @Glenn,刚刚做到了 :)

标签: ios swift nsattributedstring nsmutableattributedstring


【解决方案1】:

将标签的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. 右对齐和居中对齐最多一行

请关注此post 以获得完整的解决方案。

【讨论】:

  • 看我的回答。 :)
【解决方案2】:

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

我意识到除了使用这个 pod 之外我找不到任何其他解决方案:TTTAttributedLabelhttps://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))

}

结果:

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 2012-11-21
    • 2016-01-12
    • 1970-01-01
    • 2023-02-24
    • 2020-12-31
    • 1970-01-01
    相关资源
    最近更新 更多