Обновление значения UITextView из shouldChangeTextIn возвращает символ дважды - PullRequest
0 голосов
/ 18 июня 2019

Я хочу реализовать HasTag в UITextView, когда пользователь печатает текст в UITextView.

Для этого я попробовал ниже код.

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if text == "\n" {
        self.txtB.resignFirstResponder()
        return false
    }

    let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
    let numberOfChars = newText.count

    self.txtB.attributedText = CommonHelper.sharedInstance.convert(self.txtB.text.findMentionText(), string: self.txtB.text)
    return numberOfChars < 121 //120 limit
}

Функции HasTag

func findMentionText() -> [String] {
    var arr_hasStrings:[String] = []
    let regex = try? NSRegularExpression(pattern: "(#[a-zA-Z0-9_\\p{Arabic}\\p{N}]*)", options: [])
    if let matches = regex?.matches(in: self, options:[], range:NSMakeRange(0, self.count)) {
        for match in matches {
            arr_hasStrings.append(NSString(string: self).substring(with: NSRange(location:match.range.location, length: match.range.length )))
        }
    }
    return arr_hasStrings
}


func convert(_ hashElements:[String], string: String) -> NSAttributedString {
    let hasAttribute = [NSAttributedString.Key.foregroundColor: UIColor.orange, NSAttributedString.Key.font: UIFont.init(name: Fonts.PoppinsBoldItalic, size: 16.0)]
    let normalAttribute = [NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.font: UIFont.init(name: Fonts.PoppinsBoldItalic, size: 16.0)]

    let mainAttributedString = NSMutableAttributedString(string: string, attributes: normalAttribute)
    let txtViewReviewText = string as NSString

    hashElements.forEach { if string.contains($0) {
        mainAttributedString.addAttributes(hasAttribute, range: txtViewReviewText.range(of: $0))
        }
    }
    return mainAttributedString
}

Если я наберу один символ, то в текстовом представлении этот символ будет дважды.

как это исправить?

1 Ответ

1 голос
/ 18 июня 2019

В следующих строках

self.txtBeep.attributedText = CommonHelper.sharedInstance.convert(self.txtB.text.findMentionText(), string: self.txtB.text)

return numberOfChars < 121 //120 limit
  1. В line-1 вы устанавливаете text в textView согласно вашему требованию.

  2. В line-2 , если numberOfChars < 121, true будет returned, что означает append the text to the textView.

По этой причине text вводится дважды в textView в случае numberOfChars < 121.

Решение:

Метод textView(_:shouldChangeTextIn:replacementText:) должен быть таким,

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if text == "\n" {
        self.txtB.resignFirstResponder()
        return false
    }

    let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
    let numberOfChars = newText.count
    if numberOfChars > 120 {
        return false
    }

    self.txtB.attributedText = CommonHelper.sharedInstance.convert(newText.findMentionText(), string: newText)
    return false
}
...