Underline button text in Swift

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

    Based on some of previous answers I decide to make a class that can be easy implemented into your apps

    Swift 4

    import UIKit
    
    class UnderlineTextButton: UIButton {
    
    override func setTitle(_ title: String?, for state: UIControlState) {
        super.setTitle(title, for: .normal)
        self.setAttributedTitle(self.attributedString(), for: .normal)
    }
    
    private func attributedString() -> NSAttributedString? {
        let attributes : [NSAttributedStringKey : Any] = [
            NSAttributedStringKey.font : UIFont.systemFont(ofSize: 19.0),
            NSAttributedStringKey.foregroundColor : UIColor.red,
            NSAttributedStringKey.underlineStyle : NSUnderlineStyle.styleSingle.rawValue
        ]
        let attributedString = NSAttributedString(string: self.currentTitle!, attributes: attributes)
        return attributedString
      }
    }
    

    From code I call it on such a way button.setTitle(author, for: .normal)

提交回复
热议问题