Underline button text in Swift

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

    Swift 5 / Xcode 11

      @IBOutlet weak var myButton: UIButton!
    
      let yourAttributes: [NSAttributedString.Key: Any] = [
          .font: UIFont.systemFont(ofSize: 14),
          .foregroundColor: UIColor.blue,
          .underlineStyle: NSUnderlineStyle.single.rawValue]
             //.double.rawValue, .thick.rawValue
    
      override func viewDidLoad() {
         super.viewDidLoad()
    
         let attributeString = NSMutableAttributedString(string: "Your button text",
                                                         attributes: yourAttributes)
         myButton.setAttributedTitle(attributeString, for: .normal)
      }
    

    Swift 4 / Xcode 9

      @IBOutlet weak var myButton: UIButton!
    
      let yourAttributes : [NSAttributedStringKey: Any] = [
          NSAttributedStringKey.font : UIFont.systemFont(ofSize: 14),
          NSAttributedStringKey.foregroundColor : UIColor.blue,
          NSAttributedStringKey.underlineStyle : NSUnderlineStyle.styleSingle.rawValue]
             //.styleDouble.rawValue, .styleThick.rawValue, .styleNone.rawValue
    
      override func viewDidLoad() {
        super.viewDidLoad()
    
        let attributeString = NSMutableAttributedString(string: "Your button text",
                                                        attributes: yourAttributes)
        myButton.setAttributedTitle(attributeString, for: .normal)
      }
    

    Swift 3 / Xcode 8

      @IBOutlet weak var myButton: UIButton!
    
      let yourAttributes : [String: Any] = [
          NSFontAttributeName : UIFont.systemFont(ofSize: 14),
          NSForegroundColorAttributeName : UIColor.white,
          NSUnderlineStyleAttributeName : NSUnderlineStyle.styleSingle.rawValue] 
             //.styleDouble.rawValue, .styleThick.rawValue, .styleNone.rawValue
    
       override func viewDidLoad() {
          super.viewDidLoad()
    
          let attributeString = NSMutableAttributedString(string: "Your button text", 
                                                           attributes: yourAttributes)        
          myButton.setAttributedTitle(attributeString, for: .normal) 
        }
    

提交回复
热议问题