簡體   English   中英

UITextView / NSAttribute:檢測單詞是否以特定符號開頭

[英]UITextView/NSAttribute: Detect if word starts with a particular symbol

我一直在尋找一種方法來更改單詞以"@""#"開頭的UITextView的文本。 我在下面的StackOverflow上找到了此代碼段 ,如果您鍵入"Hello""World" ,則可以完美地運行。

我如何調整此代碼,以便它可以檢測單詞是否以“ @”或“#”開頭,​​后跟空格之前的任意數量的字符,並應用相同的樣式?

如果用戶以"@""#"開頭的“單詞”,則結果將導致UITextView本的顏色改變。 即:

快速的棕色#fox跳過了@lazydog

func textViewDidChange(_ textView: UITextView) {
    let defaultAttributes = mediaDescription.attributedText.attributes(at: 0, effectiveRange: nil)
    let attrStr = NSMutableAttributedString(string: textView.text, attributes: defaultAttributes)
    let inputLength = attrStr.string.count
    let searchString : NSArray = NSArray.init(objects: "hello", "world")
    for i in 0...searchString.count-1
    {
        let string : String = searchString.object(at: i) as! String
        let searchLength = string.count
        var range = NSRange(location: 0, length: attrStr.length)

        while (range.location != NSNotFound) {
            range = (attrStr.string as NSString).range(of: string, options: [], range: range)
            if (range.location != NSNotFound) {
                attrStr.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location: range.location, length: searchLength))
                attrStr.addAttribute(NSAttributedStringKey.font, value: UIFont(name: "Karla-Regular", size: 16.0)!, range: NSRange(location: range.location, length: searchLength))
                range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
                textView.attributedText = attrStr
            }
        }
    }
}

假設您在文本中保留#@ ,則可以修改Larme注釋中的答案:

let regex = try! NSRegularExpression(pattern: "(?:#|@)\\w+", options: [])

func textViewDidChange(_ textView: UITextView) {
    let attrStr = NSMutableAttributedString(attributedString: textView.attributedText ?? NSAttributedString())
    let plainStr = attrStr.string
    attrStr.addAttribute(.foregroundColor, value: UIColor.black, range: NSRange(0..<plainStr.utf16.count))

    let matches = regex.matches(in: plainStr, range: NSRange(0..<plainStr.utf16.count))

    for match in matches {
        let nsRange = match.range
        let matchStr = plainStr[Range(nsRange, in: plainStr)!]
        let color: UIColor
        if matchStr.hasPrefix("#") {
            color = .red
        } else {
            color = .blue
        }
        attrStr.addAttribute(.foregroundColor, value: color, range: nsRange)
    }

    textView.attributedText = attrStr
}

我只是更改了模式,以適應Swift 4.1,修復了一些錯誤,刪除了一些冗余代碼,並添加了一些代碼來更改顏色。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM