gpt4 book ai didi

ios - 下划线覆盖 NSAttributedString 中的文本

转载 作者:行者123 更新时间:2023-11-28 09:32:12 26 4
gpt4 key购买 nike

我正在尝试创建一个属性字符串,但下划线覆盖了我的文本而不是出现在它后面:

enter image description here

有办法解决这个问题吗?我正在使用以下代码:

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)

谢谢!

编辑:

提供更多上下文:

我在 .xib 文件中的 UILabel 上显示属性字符串:

view.textLabel.attributedText = attributedString

标签具有以下字体:系统粗体 32.0

我在 iPhone 6 - iOS 10.3 模拟器上运行代码。

编辑 2:

我应该提到标签在某些时候可能包含多行文本。这就是将 numberOfLines 设置为 0 的原因。

编辑 3:如果有人遇到这个问题——在 iOS 9 和 10 以及 UILabel 和 UITextView 上下划线的绘制方式似乎有很多不同。我最终不得不通过子类化 NSLayoutManager 自己绘制下划线。

最佳答案

是的,确实存在您描述的问题。它在您使用多行 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)

一切都会很好看。

但是如果你想使用这样的文本:

label.attributedText = NSAttributedString(string: "String to\ntest underline", attributes: selectedStringAttributes)

或者标签的宽度太短,比:

Not so good

所以这种行为的原因当然是bugNSAttributedString 中。正如雷达中提到的那样,有一个解决方法

您应该将此属性添加到您的 NSAttributedString

NSBaselineOffsetAttributeName: 0

奇迹将会发生。

关于ios - 下划线覆盖 NSAttributedString 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43785665/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com