Grz*_*ski 1 nsattributedstring ios swift
我正在尝试创建一个属性字符串,但下划线覆盖了我的文本而不是出现在它后面:
有没有办法来解决这个问题?我正在使用以下代码:
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 10.0
let attributes = [NSForegroundColorAttributeName: UIColor.white,
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleThick.rawValue,
NSUnderlineColorAttributeName: UIColor.red,
NSParagraphStyleAttributeName: paragraphStyle]
let attributedString = NSAttributedString(string: "Story", attributes: attributes)
Run Code Online (Sandbox Code Playgroud)
谢谢!
编辑:
提供更多上下文:
我在放置在 .xib 文件中的 UILabel 上显示属性字符串:
view.textLabel.attributedText = attributedString
Run Code Online (Sandbox Code Playgroud)
标签的字体如下: System Bold 32.0
我在 iPhone 6 - iOS 10.3 模拟器上运行代码。
编辑2:
我应该提到标签在某些时候可能包含不止一行文本。这就是 numberOfLines 设置为 0 的原因。
编辑 3:如果有人遇到这个问题——似乎在 iOS 9 和 10 以及 UILabel 和 UITextView 上绘制下划线的方式有很大不同。我最终不得不通过继承 NSLayoutManager 自己绘制下划线。
小智 5
是的,有你描述的问题。它会在您使用 multiline 时显示UILabel,因此不仅设置numberOfLines为 0,而且在其中键入多于 1 行。
例子
let selectedStringAttributes: [String: Any]
= [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 28),
NSForegroundColorAttributeName: UIColor.green,
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue,
NSUnderlineColorAttributeName: UIColor.green]
let label = UILabel(frame: CGRect(x: 100, y: 100, width: 500, height: 100))
label.numberOfLines = 0
label.attributedText = NSAttributedString(string: "String to test underline", attributes: selectedStringAttributes)
Run Code Online (Sandbox Code Playgroud)
一切都会看起来很不错。
但是如果你想使用这样的文字:
label.attributedText = NSAttributedString(string: "String to\ntest underline", attributes: selectedStringAttributes)
Run Code Online (Sandbox Code Playgroud)
或标签的宽度太短,比:
所以,对这种行为的原因当然是错误在NSAttributedString。正如它在雷达中提到的,有一个解决方法
您应该将此属性添加到您的 NSAttributedString
NSBaselineOffsetAttributeName: 0
Run Code Online (Sandbox Code Playgroud)
魔法会发生。
| 归档时间: |
|
| 查看次数: |
3479 次 |
| 最近记录: |