带删除线的多行属性字符串

Multiline attributed string with strikethrough

我有一个标签:

label.numberOfLines = 0

我正在尝试使用以下方法为该标签的文本添加删除线:

let index: NSMutableAttributedString = NSMutableAttributedString(string: label.text!)
index.addAttributes([NSStrikethroughStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue, NSStrikethroughColorAttributeName: UIColor.red], range: NSMakeRange(0, index.length))
label.textColor = UIColor.red
label.attributedText = index

属性字符串是否不适用于多行或 numberOfLines 设置为 0 的标签?如果是这样,如何使多行文本删除线?

你的代码应该是这样的,

 let index: NSMutableAttributedString = NSMutableAttributedString(string: lbl.text!)
    index.addAttributes([NSStrikethroughStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue, NSStrikethroughColorAttributeName: UIColor.red], range: NSMakeRange(0, index.length))
    lbl.textColor = UIColor.red
    lbl.attributedText = index

因为 index 是您的可变字符串!不是标题!

并且您不能将 strike throughmulti line 标签一起使用。

如果你想要 strike through 多行效果那么你可以使用 UITextView 而不是标签!

这样写,

    self.label.numberOfLines = 0
    let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: self.label.text!)
    attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 1, range: NSMakeRange(0, attributeString.length))
    self.label.attributedText = attributeString

在我这边工作。

我想到了两个解决方案。它们基于@SivajeeBattina 的回答。

第一个是在 http://adamvarga.com/strike/ 的帮助下删除文本。

private func returnStrikedOutTextFromString(_ str: String) -> String {
    var newString = ""

    let normal = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя "
    let strikethrough = "А̶Б̶В̶Г̶Д̶Е̶Ё̶Ж̶З̶И̶Й̶К̶Л̶М̶Н̶О̶П̶Р̶С̶Т̶У̶Ф̶Х̶Ц̶Ч̶Ш̶Щ̶Ъ̶Ы̶Ь̶Э̶Ю̶Я̶а̶б̶в̶г̶д̶е̶ё̶ж̶з̶и̶й̶к̶л̶м̶н̶о̶п̶р̶с̶т̶у̶ф̶х̶ц̶ч̶ш̶щ̶ъ̶ы̶ь̶э̶ю̶я̶ ̶̶"

    for i in 0..<str.characters.count {

        let range: Range<String.Index> =
                normal.range(of: str
                        .substring(to: str.index(str.startIndex, offsetBy: i + 1))
                        .substring(from: str.index(str.startIndex, offsetBy: i)))!
        let index: Int = normal.distance(from: normal.startIndex, to: range.lowerBound)

        newString = String(format: "%@%@", newString,
                NSLocalizedString(strikethrough
                        .substring(to: strikethrough.index(strikethrough.startIndex, offsetBy: index + 1))
                        .substring(from: strikethrough.index(strikethrough.startIndex, offsetBy: index)),
                        comment: ""))

    }

    return newString

}

第二个是:https://github.com/GuntisTreulands/UnderLineLabel

如果您在之前添加 NSBaselineOffsetAttributeName,则可以很好地处理多行:

let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: (object?.title)!)
attributeString.addAttribute(NSBaselineOffsetAttributeName, value: 0, range: NSMakeRange(0, attributeString.length))
attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))