Underline button text in Swift

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

    Here you can add an underline and bold face too. You can just add an extention in your swift class file

    Here is the extention (Swift 4 updated)

    extension NSMutableAttributedString {
     @discardableResult func bold(_ text:String) -> NSMutableAttributedString {
    
          let attrs : [NSAttributedStringKey : Any] = [
            NSAttributedStringKey.font : UIFont(name: "Montserrat-Bold", size: 12)!,
            NSAttributedStringKey.foregroundColor : UIColor.white,
            NSAttributedStringKey.underlineStyle : NSUnderlineStyle.styleSingle.rawValue]
        let boldString = NSMutableAttributedString(string: text, attributes: attrs)
        self.append(boldString)
        return self
     }
    
     @discardableResult func normal(_ text:String)->NSMutableAttributedString {
          let attrs : [NSAttributedStringKey : Any] = [
            NSAttributedStringKey.font : UIFont(name: "Montserrat-Regular", size: 12)!,
            NSAttributedStringKey.foregroundColor : UIColor.white
        ]
        let normal =  NSAttributedString(string: text,  attributes:attrs)
        self.append(normal)
        return self
     }
    

    }

    You can use it like this:

    let FormattedText = NSMutableAttributedString()
          FormattedText
               .normal("By signing in, you agree with our ")
               .bold("Terms of Service")
    
    yourLabel.attributedText = FormattedText
    

    and the Result will be display like this

提交回复
热议问题