Search code examples
iosswiftswift3uilabelnsattributedstring

Multiline attributed string with strikethrough


I have a label with:

label.numberOfLines = 0

And I'm trying to make text of this label strikethrough with:

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

Is it true that attributed string is not working with multilines or with labels with numberOfLines set to 0? And if so, how to make multiline text strikethrough?


Solution

  • I came up with two solutions. They are based on @SivajeeBattina answer.

    First one is to strike out text with help of 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
    
    }
    

    And second one is: https://github.com/GuntisTreulands/UnderLineLabel