所以我确实花了 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))
}
结果:
我希望这会有所帮助!