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

后端 未结 7 546
佛祖请我去吃肉
佛祖请我去吃肉 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:54

    Swift 5 version of @Joss's answer with few modifications, by adding a returned NSMutableAttributedString, because I couldn't use the original solution without it.

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

    Usage:

     let myUnderLinedText = "Hello World"
     let underLinedMutableString =  NSMutableAttributedString(string: myUnderLinedText, attributes: titleAttributes).underline(term: myUnderLinedText)
    
    0 讨论(0)
提交回复
热议问题