I want the underline to be below the text like any other normal underlining mechanism. However, with NSAttributed string it leaves holes with "g's" and "y's"
example:
How it should look:
How can I increase the spacing between the underline and label?
To make the text on UILabel underlined we will need to use the NSMutableAttributedString together with NSUnderlineStyleAttributeName. The Swift code snippet below demonstrates how to create a new UILabel programmatically and then use the NSMutableAttributedString to underline the text on the label.
swift 3/4/5 Select button or label title as Attributed. Select range of text which you want to underline. Right click and choose Font then select underline.
An NSAttributedString object manages character strings and associated sets of attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string. An association of characters and their attributes is called an attributed string.
Usage: let label = UILabel() label. attributedText = NSMutableAttributedString() . bold("Address: ") .
There is no way to control that behaviour with NSAttributedString
or CoreText (apart from drawing the underline yourself). NSAttributedString has no option for that (and CoreText hasn't got one, either).
On Apple systems, the first version (with the gap) is the "expected" behaviour as it's the one Apple provides and is used throughout the system (and apps like Safari, TextEdit, etc.).
If you really, really want to have underlines without a gap, you need to draw the string without an underline and draw the line yourself (which I needed to do in one of my projects and I can tell you it's hard; see this file, search for "underline").
I added a line (UIView) with height 1 and width like label, aligned to the bottom of the UILabel.
let label = UILabel() label.text = "underlined text" let spacing = 2 // will be added as negative bottom margin for more spacing between label and line let line = UIView() line.translatesAutoresizingMaskIntoConstraints = false line.backgroundColor = label.textColor label.addSubview(line) label.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[line]|", metrics: nil, views: ["line":line])) label.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[line(1)]-(\(-spacing))-|", metrics: nil, views: ["line":line]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With