同一UITextView中的字符串和AtttributedString

问题描述 投票:0回答:1

我可以在同一String中使用NSMutableAttributedStringUITextView吗?

我正在导入.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”并更改其颜色

实现我所追求的最好的方法是什么?

ios swift string uitextview nsmutableattributedstring
1个回答
0
投票

这是实现您想要的方式

// set your textview delegate in your view controller

class ViewController: UIViewController,UITextViewDelegate {

@IBOutlet weak var txtView: UITextView!
override func viewDidLoad() {
    super.viewDidLoad()
    txtView.delegate = self
    // Do any additional setup after loading the view.
}


// and implement didchange method

func textViewDidChange(_ textView: UITextView) {
    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
    }

}
}
© www.soinside.com 2019 - 2024. All rights reserved.