How do you use NSAttributedString?

后端 未结 15 1114
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 04:19

Multiple colours in an NSString or NSMutableStrings are not possible. So I\'ve heard a little about the NSAttributedString which was introduced wit

15条回答
  •  长发绾君心
    2020-11-22 04:54

    An easier solution with attributed string extension.

    extension NSMutableAttributedString {
    
        // this function attaches color to string    
        func setColorForText(textToFind: String, withColor color: UIColor) {
            let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive)
            self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
        }
    
    }
    

    Try this and see (Tested in Swift 3 & 4)

    let label = UILabel()
    label.frame = CGRect(x: 120, y: 100, width: 200, height: 30)
    let first = "first"
    let second = "second"
    let third = "third"
    let stringValue = "\(first)\(second)\(third)"  // or direct assign single string value like "firstsecondthird"
    
    let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
    attributedString.setColorForText(textToFind: first, withColor: UIColor.red)   // use variable for string "first"
    attributedString.setColorForText(textToFind: "second", withColor: UIColor.green) // or direct string like this "second"
    attributedString.setColorForText(textToFind: third, withColor: UIColor.blue)
    label.font = UIFont.systemFont(ofSize: 26)
    label.attributedText = attributedString
    self.view.addSubview(label)
    

    Here is expected result:

    enter image description here

提交回复
热议问题