How to display Underlined Text in a Button on iOS?

Warrior picture Warrior · Apr 15, 2010 · Viewed 27k times · Source

I want to display the mail ID in my view such that clicking the mail ID should open the mail composer view.

I want to display the button text as underlined to show it is a hyperlink and for the button click event to call the mail composer view. At present, I am not able to show the button text underlined.

I thought of placing a label above the button and adjusting the label property to get the underlined text but that did not work.

Is there a different way to get the appearance and behavior I want?

Answer

Robert Chen picture Robert Chen · Jan 28, 2016

Adding a screenshot for @Haider's answer.

Note: Only the text you highlight gets underlined, so you can underline just a specific range if you want.

enter image description here

I ended up underlining it in code anyway, just because I couldn't get Bold to work in conjunction with Underline for some reason. Could have been because of the font I was using, who knows.

@IBOutlet weak var underlineButton: UIButton! {
    didSet {
        let attrs = [
            NSFontAttributeName : UIFont(name: "MyCustomFont-Bold", size: 19.0)!,
            NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue,
            NSForegroundColorAttributeName : UIColor.orangeColor()
        ]
        let attrString = NSMutableAttributedString(string: "Button text", attributes:attrs)
        underlineButton.setAttributedTitle(attrString, forState: .Normal)
    }
}