同一 UITextView 中的 String 和 AtttributedString

String and AtttributedString in the same UITextView

我可以在同一个 UITextView 中使用 StringNSMutableAttributedString 吗?

我正在导入一个 .docx 文件并转换为 String,然后我将其显示在 UITextField 中,但我想为特定单词着色。理想情况下,用户会键入 "LineBreak",它会自动将 LineBreak 一词更改为不同的颜色

据我了解,这需要使用 NSMutableAttributedString,但我不知道该怎么做

let string = "Test Specific Colour LineBreak TestLine2"
let attributedString = NSMutableAttributedString.init(string: string)
let range = (string as NSString).range(of: "LineBreak")
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, 
value: UIColor.blue, range: range)
txtView.attributedText = attributedString

所以使用上面的示例,我希望 "LineBreak" 的颜色在每次输入时都发生变化。上面的方法可以改变颜色,但不是每次我输入它。我需要识别字符串 "LineBreak" 存在并更改其颜色

实现我所追求的目标的最佳方法是什么?

这里有一个方法可以实现你想要的

// set your textview delegate in your view controller if you are using textview
// set the target if you are using textfield
// textfield.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)

class ViewController: UIViewController,UITextViewDelegate {

@IBOutlet weak var textfield: UITextField!
@IBOutlet weak var txtView: UITextView!
override func viewDidLoad() {
    super.viewDidLoad()
    txtView.delegate = self
    textfield.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)

    // Do any additional setup after loading the view.
}


// if you are using textview implement this

func textViewDidChange(_ textView: UITextView) {
    print(textView.text)
    let string = textView.text

    if textView.text.contains("LineBreak") {
        let attributedString = NSMutableAttributedString.init(string: textView.text)
        let range = (string as! NSString).range(of: "LineBreak")
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor,
        value: UIColor.blue, range: range)
        textView.attributedText = attributedString
    }

}

// if you are using textfield you need to
// add this line in your didload
//textfield.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
// and implement this function

@objc func textFieldDidChange() {
    let string = textfield.text

    if textfield.text!.contains("LineBreak") {
        let attributedString = NSMutableAttributedString.init(string: textfield.text!)
               let range = (string as! NSString).range(of: "LineBreak")
               attributedString.addAttribute(NSAttributedString.Key.foregroundColor,
               value: UIColor.blue, range: range)
               textfield.attributedText = attributedString
           }
    }
}

输出:

这是一种让您入门的方法...

确保您的控制器符合 UITextViewDelegate 并且您已经分配了文本视图的委托:

class ExampleViewController: UIViewController, UITextViewDelegate {

    @IBOutlet var theTextView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        theTextView.delegate = self
        theTextView.text = "Test Specific Colour LineBreak TestLine2 linebreak and another LineBreak occurance"
        formatTextInTextView(theTextView)
    }

    func textViewDidChange(_ textView: UITextView) {
        formatTextInTextView(textView)
    }

    func formatTextInTextView(_ textView: UITextView) -> Void {
        guard let curText = textView.text else { return }

        let bScroll = textView.isScrollEnabled
        textView.isScrollEnabled = false
        let selRange = textView.selectedRange

        let attributedString = NSMutableAttributedString.init(string: curText)

        let regex = try! NSRegularExpression(pattern: "LineBreak", options: [.caseInsensitive])
        let items = regex.matches(in: curText, options: [], range: NSRange(location: 0, length: curText.count))
        let ranges: [NSRange] = items.map{[=10=].range}
        for r in ranges {
            attributedString.addAttribute(.foregroundColor, value: UIColor.red, range: r)
        }
        textView.attributedText = attributedString
        textView.selectedRange = selRange
        textView.isScrollEnabled = bScroll
    }

}

您可能希望将其限制为区分大小写、全字等...