Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSUnderlineStyleAttributeName Underline spacing

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: enter image description here

How it should look: enter image description here

How can I increase the spacing between the underline and label?

like image 849
MobileMon Avatar asked Dec 30 '14 18:12

MobileMon


People also ask

How do you underline text in a swift 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.

How do you underline a button title in Swift?

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.

What is NSAttributedString?

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.

How do you bold a string in Swift?

Usage: let label = UILabel() label. attributedText = NSMutableAttributedString() . bold("Address: ") .


2 Answers

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").

like image 118
DarkDust Avatar answered Oct 05 '22 00:10

DarkDust


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])) 
like image 22
Ferran Maylinch Avatar answered Oct 05 '22 01:10

Ferran Maylinch