Adding underline to UILabel attributed string from the storyboard fails

后端 未结 6 1795
半阙折子戏
半阙折子戏 2021-01-30 12:22
  1. From the storyboard I select the UILabel in question
  2. Then in Attribute Inspector > Label > [I choose] Attributed
  3. Also in Attribute Inspector > Label > Te
6条回答
  •  生来不讨喜
    2021-01-30 13:13

    You can make text underline from storyboard like this. But when you change the text programatically it will override and underline will gone. So if you have to change the text on runtime. Do this.

    For Swift 3

     let text = myLabel.text
     let textRange = NSMakeRange(0, (text?.characters.count)!)
     let attributedText = NSMutableAttributedString(string: text!)
     attributedText.addAttribute(NSUnderlineStyleAttributeName , value: NSUnderlineStyle.styleSingle.rawValue, range: textRange)
     myLabel.attributedText = attributedText
    

    For Swift 4

      let text = myLabel.text
      let textRange = NSRange(location: 0, length: (text?.count)!)
      let attributedText = NSMutableAttributedString(string: text!)
      attributedText.addAttribute(NSAttributedStringKey.underlineStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: textRange)
      myLabel.attributedText = attributedText
    

提交回复
热议问题