为什么删除线在iOS 14中不起作用

问题描述

我有一个UILabel,它显示删除线文本(例如 text )。直到iOS 13都可以正常工作。在iOS 14中,删除线没有显示,即不是' text ',而是'text'。这是我使用的代码

let totalString: String = "some text"
let strikeString: String = "text" //string to be made strikethrough
let totalNsstring = totalString as Nsstring
let attributeString =  NSMutableAttributedString(string: totalString)
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle,value: 2,range: totalNsstring.range(of: strikeString))
label.attributedText = attributeString

所需的输出

一些文本

当前出站次数

一些文字

任何人都可以告诉我是否有需要更改的内容或其他内容。 TIA。

解决方法

无法复制。我复制了您的代码,没有任何更改并运行了它,这就是我在模拟器中看到的:

enter image description here

这就是我希望看到的,以及您声称希望看到的。因此,如果您没有看到,那是由于其他一些原因。也许label不是您认为的UILabel。也许其他代码会随之而来并更改文本。但是无论原因为何,都与提出的问题无关。

(考虑到实践和易读性,最好用NSUnderlineStyle.thick.rawValue而不是2。但这与这里的问题无关。)

,

在属性字符串中添加值为0的baselineOffset将删除线删除。可以在apple dev forumthis SO thread上找到更多详细信息。

attributeString.addAttribute(NSAttributedString.Key.baselineOffset,value: 0,range: totalNsString.range(of: strikeString))
,

解决办法是使用strikethroughStyle,还要设置strikethroughColor:

let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: text,attributes: [:])
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle,value: NSUnderlineStyle.single.rawValue,range: NSRange(location: 0,length: attributeString.length))
attributeString.addAttribute(NSAttributedString.Key.strikethroughColor,value: UIColor.black,length: attributeString.length))
,
let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "Text")
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle,value: 5,range: NSMakeRange(0,attributeString.length))
label.attributedText = attributeString