Underline button text in Swift

后端 未结 14 1849
暖寄归人
暖寄归人 2021-01-30 10:26

I have UIButton. In interface builder I set its title to be \'Attributed\'. How can I make its title to be underlined from code in Swift?

@IBOutlet weak var myBt         


        
14条回答
  •  遇见更好的自我
    2021-01-30 10:32

    This is my solution. And to be honest you probably need this more than one place, so let's create an extension. This is swift 5.0 Cheers :)

    extension UIButton {
        func underline() {
            guard let title = self.titleLabel else { return }
            guard let tittleText = title.text else { return }
            let attributedString = NSMutableAttributedString(string: (tittleText))
            attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: (tittleText.count)))
            self.setAttributedTitle(attributedString, for: .normal)
        }
    }
    

    And you can use it like this.

        override func viewDidLoad() {
         super.viewDidLoad()
         button.underline()
    }
    

提交回复
热议问题