So I did spend 45 minutes just to find a solution to this problem. I've been using my own UILabel extension for highlighting texts but unfortunately it highlights the empty spaces or rather the indent spaces when the textAlignment is set to right, like this problem of yours.
I realised I couldn't find any other solution rather than using this pod: TTTAttributedLabel
https://github.com/TTTAttributedLabel/TTTAttributedLabel
This handles setting attributed string to the UILabel
very well. The pod though was written in Objective-C, so you'll need a bridging header for that. I suppose you already know how to port Objective-C codes into your Swift projects.
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))
}
Result:

I hope this helps!