Underline part of a string using NSMutableAttributedString in iOS 8 is not working

后端 未结 7 549
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 12:11

I try to underline part of a string, for example, a \'string\' part in \'test string\' string. I\'m using NSMutableAttributedString and my sol

7条回答
  •  轮回少年
    2020-12-13 12:42

    It's September 2018, so this answer is not about iOS8 but it still relates to underlining part of a string.

    Here is a Swift 4 extension that underlines a given term within an already composed myAttributedString

    extension NSMutableAttributedString {
    
        func underline(term: String) {
    
            guard let underlineRange = string.range(of: term) else {
    
                return
            }
    
            let startPosition = string.distance(from: term.startIndex, to: underlineRange.lowerBound)
            let nsrange = NSRange(location: startPosition, length: term.count)
    
            addAttribute(
                .underlineStyle,
                value: NSUnderlineStyle.styleSingle.rawValue,
                range: nsrange)
        }
    }
    

    Usage: myAttributedString.underline(term: "some term")

提交回复
热议问题