Home > Mobile >  how to make underline use Swift?
how to make underline use Swift?

Time:06-16

sample text image

I want to draw underline like picture. but "NSUnderlineStyleAttributeName" is not working please help me

CodePudding user response:

You can do this using NSAttributedString

Example :

 let underlineAttribute = [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.thick.rawValue]
 let underlineAttributedString = NSAttributedString(string: "StringWithUnderLine", attributes: underlineAttribute)
 YourLabel.attributedText = underlineAttributedString

Extension

extension UILabel {
func underline() {
    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))
      attributedText = attributedString
    }
}
}
  • Related