Why is underline style not working for a NSAttributedString? [duplicate]
Asked Answered
T

1

6

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.

Testes answered 30/7, 2021 at 14:59 Comment(5)
.underlineStyle: NSUnderlineStyle.single.rawValueDrover
Try with TextView. It will workIlliberal
@Illiberal There are reasons why using TextView might not be desired in this case.Testes
@CharlieFish I have faced this too But I ended up using TextView for this bugIlliberal
@Illiberal 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.Testes
T
11

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
Testes answered 30/7, 2021 at 14:59 Comment(2)
how can i get this answer from somewhere... big thxUpcoming
you're holding it wrong. see https://mcmap.net/q/966899/-how-to-get-nsattributedstring-39-s-underline-style-attribute-to-workCustodial

© 2022 - 2024 — McMap. All rights reserved.