Using NSAttributedString, I would like to underline a portion of a string. The following code does not work as expected:
let string = NSMutableAttributedString(string: "This is my string.")
string.addAttributes([.underlineStyle : NSUnderlineStyle.single],
range: NSRange(location: 5, length: 2))
Run Code Online (Sandbox Code Playgroud)
One expects "is" to be underlined. Instead, the UITextView layout engine ignores the attribute, and generates a warning in the console. Unhelpfully, the warning makes no mention of underlineStyle or NSUnderlineStyle.
这个问题很常见。StackOverflow上有很多示例显示了正确的用法。但是,虽然我确定必须有一些答案可以解释该问题,但我已阅读的答案仅显示了用法的不透明示例。
提出这个问题(并在下面给出答案)是为了纪念对该问题的解释,以便将来我和其他人可以从中学习。