Eddie
Eddie

Reputation: 1941

UILabel underline text with high characters below baseline

I'd like to make underlined text for a UILabel. For now, I'm using:

self.lbValue.attributedText = NSAttributedString(string: value, attributes: 
    [NSUnderlineStyleAttributeName : NSUnderlineStyle.styleSingle.rawValue])

It does draw a single line under the text, that's alright. However, when the character is high (and fall below the base line), it crops the line and makes ugly blank space between the line, like this:

high characters

As you can see, there's a tiny dot below the characters. That's where my underline go. How do I make a solid line and overlaps the characters? Like this:

Expected output

I've tried other style (dash, dot, thick, solid...) none of them work as I expected.

Upvotes: 0

Views: 615

Answers (2)

Tushar Sharma
Tushar Sharma

Reputation: 2882

This can be achieved in other better way as well.I will show you an example-:

1) Add a label and, UIView below that label(Which will work as underline).

2) Provide appropriate constraints.

Check image Below-:

Label Constraints-:

enter image description here

Underline View Constraints-:

enter image description here

Now in controller class add Outlets. And, also add width NSLayoutConstraint for underline UIView.

As I suppose your label width can change dynamically we will give underline label(Width) an intrinsicContentSize . This will adjust underline label width based upon content in UILabel.

Controller Class-:

import UIKit

class UnderlineViewController: UIViewController {


    @IBOutlet weak var myLabel: UILabel!
    @IBOutlet weak var underLineWidth: NSLayoutConstraint!
    @IBOutlet weak var underline: UIView!


    override func viewDidLoad() {
        super.viewDidLoad()
        // SET TEXT FOR LABEL
        myLabel.text = "What's next in Game Of Thrones"
        // MAKE UNDERLINE VIEW WIDTH INTTRINSIC
        underLineWidth.constant = myLabel.intrinsicContentSize.width
        // Do any additional setup after loading the view.

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Output-:

enter image description here

enter image description here

Hope it helps you.

Upvotes: 1

jegadeesh
jegadeesh

Reputation: 945

I am suggesting you to add a label with height as 1 and width equal to the width of the label and pin it below the content label(set background colour of the label to your desired underline color).

This may not be a solution which you were expecting, but it will solve the requirement. :)

Upvotes: 0

Related Questions