Underline button text in Swift

后端 未结 14 1963
暖寄归人
暖寄归人 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:37

    A modified version of @shlomo-koppel answer for button title, It will work if you set/change button title programmatically (like in my case I used localization)

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

提交回复
热议问题