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

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

    I used the following extension (using exidy's function) in playground/simulator and it worked fine , you may change/add attributes depending on your needs

     extension NSMutableAttributedString
    {
    
    
        func changeWordsColour(terms:[NSString])
    {
        let string = self.string as NSString
        self.addAttribute(NSForegroundColorAttributeName, value: UIColor.brownColor(), range: NSMakeRange(0, self.length))
        for term in terms
        {
            let underlineRange = string.rangeOfString(term as String)
            self.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: underlineRange)
    
        }
    }
    }
    
     let myStr = NSMutableAttributedString(string: "Change Words Colour")
     myStr.changeWordsColour(["change","Colour"])
    

提交回复
热议问题