Underlining text in UIButton

2020-01-26 13:12发布

Can anyone suggest how to underline the title of a UIButton ? I have a UIButton of Custom type, and I want the Title to be underlined, but the Interface Builder does not provide any option to do so.

In Interface Builder when you select the Font Option for a Button, it provides option to select None, Single, Double, Color but none of these provide any changes to the Title on the Button.

Any help appreciated.

18条回答
放荡不羁爱自由
2楼-- · 2020-01-26 13:21

In swift

func underlineButton(button : UIButton) {

var titleString : NSMutableAttributedString = NSMutableAttributedString(string: button.titleLabel!.text!)
titleString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleSingle.rawValue, range: NSMakeRange(0, button.titleLabel!.text!.utf16Count))
button.setAttributedTitle(titleString, forState: .Normal)}
查看更多
做自己的国王
3楼-- · 2020-01-26 13:22

For Swift 3 the following extension can be used:

extension UIButton {
    func underlineButton(text: String) {
        let titleString = NSMutableAttributedString(string: text)
        titleString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: NSMakeRange(0, text.characters.count))
        self.setAttributedTitle(titleString, for: .normal)
    }
}
查看更多
SAY GOODBYE
4楼-- · 2020-01-26 13:23

I believe it's some bug in font editor in XCode. If you using interface builder you have to change title from Plain to Attributed, open TextEdit create underlined text and copy-paste to textbox in XCode

查看更多
Anthone
5楼-- · 2020-01-26 13:24

How will one handle the case when we keep a button underlined pressed? In that case the button's textcolor changes according to highlighted color but line remains of original color. Let say if button text color in normal state is black then its underline will also have black color. The button's highlighted color is white. Keeping button pressed changes button text color from black to white but underline color remains black.

查看更多
闹够了就滚
6楼-- · 2020-01-26 13:27

To use interface builder to underline, one has to:

  • Change it to attributed
  • Highlight the text in the Attributes inspector
  • Right click, choose Font and then Underline

Underline using IB

Video someone else made https://www.youtube.com/watch?v=5-ZnV3jQd9I

查看更多
贼婆χ
7楼-- · 2020-01-26 13:28

You can do it in the interface builder itself.

  1. Select the attribute inspector
  2. Change the title type from plain to attributed

enter image description here

  1. Set appropriate font size and text alignment

enter image description here

  1. Then select the title text and set the font as underlined

enter image description here

查看更多
登录 后发表回答