4

I have the following code to try to underline a label's string.

let attributedString = NSMutableAttributedString(string: "Hello World!")
attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single, range: NSRange.init(location: 0, length: attributedString.length))
label.attributedText = attributedString

However, when running the code the label shows Hello World! with no underline.

I'm running Xcode 12.4, and using an iOS 14.4 iPhone 12 Pro Max simulator.

Charlie Fish
  • 18,491
  • 19
  • 86
  • 179
  • 6
    `.underlineStyle: NSUnderlineStyle.single.rawValue` – El Tomato Jul 30 '21 at 15:04
  • Try with TextView. It will work – Kudos Jul 30 '21 at 15:06
  • @Kudos There are reasons why using TextView might not be desired in this case. – Charlie Fish Jul 30 '21 at 15:11
  • @CharlieFish I have faced this too But I ended up using TextView for this bug – Kudos Jul 30 '21 at 15:12
  • @Kudos Yep, that might be a legit solution. Feel free to post an answer if you want to provide more detail. Likely many ways to solve this issue. Always good to share knowledge in case others run into a similar situation and having multiple answers or options is always helpful. – Charlie Fish Jul 30 '21 at 15:13

1 Answers1

10

It seems like this is a bug. Changing the value from NSUnderlineStyle.single to 1 fixes the issue.

The final code would look something like the following.

let attributedString = NSMutableAttributedString(string: "Hello World!")
attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: 1, range: NSRange.init(location: 0, length: attributedString.length))
label.attributedText = attributedString
Charlie Fish
  • 18,491
  • 19
  • 86
  • 179