Underline button text in Swift

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

    if you are looking for a way to do this without inheritance -

    swift 3/4/5

    // in swift 4 - switch NSUnderlineStyleAttributeName with NSAttributedStringKey.underlineStyle
    
    extension UIButton {
        func underline() {
            guard let text = self.titleLabel?.text else { return }
            let attributedString = NSMutableAttributedString(string: text)
            //NSAttributedStringKey.foregroundColor : UIColor.blue
            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)
        }
    }
    
    
    
    extension UILabel {
        func underline() {
            if let textString = self.text {
                let attributedString = NSMutableAttributedString(string: textString)
                attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: attributedString.length - 1))
                attributedText = attributedString
            }
        }
    }
    

提交回复
热议问题