Underline button text in Swift

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

    @ShlomoKoppel answer in Swift 4.2

    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 underlineMyText() {
            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
            }
        }
    }
    

提交回复
热议问题