我正在尝试创建一个属性字符串,但下划线覆盖了我的文本,而不是出现在它后面:
有没有办法来解决这个问题?我正在使用以下代码:
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)
Thanks!
EDIT:
提供更多背景信息:
我在 .xib 文件中的 UILabel 上显示属性字符串:
view.textLabel.attributedText = attributedString
标签具有以下字体:系统粗体 32.0
我正在 iPhone 6 - iOS 10.3 模拟器上运行代码。
EDIT 2:
我应该提到的是,标签在某些时候可能包含不止一行文本。这就是为什么 numberOfLines 设置为 0。
编辑3:
如果有人遇到这个问题——iOS 9 和 10 以及 UILabel 和 UITextView 上下划线的绘制方式似乎有很大差异。我最终不得不通过子类化 NSLayoutManager 自己绘制下划线。
是的,确实存在您所描述的问题。当您使用多行时它会出现UILabel
,所以不仅设置numberOfLines
为 0,但在其中键入多于 1 行。
Example
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)
或者标签的宽度太短,比:
所以这种行为的原因当然是bug https://openradar.appspot.com/31174934 in NSAttributedString
。正如雷达中提到的,有一个解决方法
您应该将此属性添加到您的NSAttributedString
NSBaselineOffsetAttributeName: 0
奇迹将会发生。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)