使用不间断空格和多行显示 NSAttributedString 时出现 Swift 错误

标签 swift nsattributedstring line-breaks spaces

如果这很明显,我深表歉意,但我已经搜索了一段时间,这个问题难倒了我。

我有一个 NSAttributedString 包含:

1) 一个“填空”式的子字符串,由不间断的空格组成,并在该子字符串上应用了下划线样式(例如“\u{00a0}\u{00a0}\u{00a0} "下划线样式仅应用于该子字符串;我最初使用下划线,但它们之间的空间有问题,因为我的文本具有不透明度,所以您可以看到之间的空间或重叠)

2) 字符串末尾有多个换行符,可以选择填空(例如"...\na) 第一选择\nb) 第二选择\nc) 最后选择")

然后我在 numberOfLines 设置为 0 的标签中显示这个 NSAttributedString。

这在 90% 的时间里工作正常,除了 10% 的时间,当不间断的“填空”出现在行尾的环绕距离内时,这意味着它被推到下一行(如预期的那样),它将所有其他文本向前推,并且如果在整个段落中发生足够的插入,它将最终的“选择”行(例如“\nc)最后的选择”)完全推出标签它不显示字符串的最后一行!?换句话说,我的标签 SEEMS 用于计算在应用不间断空格之前它需要多大,因此如果随后由不间断空格/子字符串创建了额外的行,则最后一行将被截断并且不会显示在全部。

是否有其他方法来创建或归因于此不间断的“填空”,以便它不会字符换行(即,将它们全部放在同一行上),但我的标签会理解/重新计算所说的非换行已经创建了额外的行?正如我提到的,我的标签已经将 numberOfLines 设置为 0;也许有某种段落样式或其他标签设置我无法找到?或者这只是一个 Swift 错误,但有人知道解决方法?

以下是我的代码的一些片段:

let underlineString = "\u{00a0}\u{00a0}\u{00a0}\u{00a0}\u{00a0}"
let myTextAttributes = [NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue): UIFont(name: "My Font", size: round(self.view.frame.width / 15)) as Any, NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue): UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 0.9)]

let myLabel = UILabel()
myLabel.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
myLabel.textAlignment = .center
myLabel.numberOfLines = 0

var myText = "What do you think about \u{00a0}\u{00a0}\u{00a0}\u{00a0}\u{00a0} and then what about this extra stuff at the end?\na) first choice\nb) second choice\nc) last choice"
var myAttributedText = NSMutableAttributedString(string:myText, attributes: myTextAttributes)
myAttributedText.addAttribute(NSAttributedStringKey.underlineStyle, value: NSUnderlineStyle.styleThick.rawValue, range: (myText as NSString).range(of:underlineString))
myLabel.attributedText = myAttributedText
self.view.addSubview(myLabel)

myLabel.translatesAutoresizingMaskIntoConstraints = false
myLabel.heightAnchor.constraint(equalToConstant: self.view.frame.height).isActive = true
myLabel.widthAnchor.constraint(equalToConstant: self.view.frame.width).isActive = true
myLabel.centerXAnchor.constraint(equalTo: myLabel.superview!.centerXAnchor).isActive = true
myLabel.centerYAnchor.constraint(equalTo: myLabel.superview!.centerYAnchor).isActive = true

非常感谢您的宝贵时间!

最佳答案

经过更多的研究,很明显 UILabel 现在在属性字符串方面有很多错误,所以不确定是否有针对上述不间断空格问题的技术解决方法。

话虽如此,我能够通过为我的“填空”子字符串切换回常规字符,将这些字符的 foregroundColor 设置为清除,然后设置 underlineColor 来解决这个特定的错误为白色,这样它就不会采用 foregroundColor。

关于使用不间断空格和多行显示 NSAttributedString 时出现 Swift 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50399799/

相关文章:

HTML 在文本区域内显示换行符

android - 如何在为 Android 共享提供的消息中获取换行符

ios - viewDidLoad 每次加载

arrays - 具有混合元素的Swift数组,为什么返回不同的结果

swift - 为调用异步方法的异步调度队列实现完成处理程序

ios - 如果更改基线偏移属性,UILabel 属性文本不能有多行

objective-c - 为什么在调用类别实例方法后仍无法获取它?

ios - 在 SDK 谷歌地图中快速绘制多边形/形状

iOS - 在 UITextView 中编辑文本会更改属性

html - 浏览器发送 "\r\n"还是 "\n"还是取决于浏览器?