I use textView(_: shouldChangeTextIn: replacementText:)
function to change the input data depending on the situation. I use range, but I can not get the Swift Range when using unicode character symbols (eg ( ͡° ͜ʖ ͡°) ). Please, tell me how it can be done?
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let maxLenthNotReached = textView.text.count + (text.count - range.length) <= maxTextLength
if maxLenthNotReached {
guard let newRange = Range(range, in: identityString) else { return false }
identityString = identityString.replacingCharacters(in: newRange, with: text)
}
return maxLenthNotReached
}
An app crash example http://take.ms/ojIJq
Update: I changed this method but I got a crash again when deleting
"entering data" ""
"testString" "༼ つ ͡° ͜ʖ ͡° ༽つ( ͡° ͜ʖ ͡"
"entering data" ""
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
debugPrint("textView.text", textView.text)
testString = textView.text.replacingCharacters(in: Range(range, in: textView.text)!, with: text)//
debugPrint("testString", testString)
return true
}
Update 1: I entered these characters in the textView
( ͡° ͜ʖ ͡°)༼ つ ͡° ͜ʖ ͡° ༽つ
Then I started to delete the characters with the right to the left after the three right few symbols were deleted ° ༽つ
, and the car emoji has left, then I can not get the range, since I put the guard and application doesn't crash, if I remove that of course there will be app crash.
Full code
class ViewController: UIViewController {
// MARK: - IBOutlets
@IBOutlet private weak var textView: UITextView! {
didSet {
textView.delegate = self
textView.text = "( ͡° ͜ʖ ͡°)༼ つ ͡° ͜ʖ ͡° ༽つ"
}
}
// MARK: - Properties
private var testString = ""
}
extension ViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard let newRange = Range(range, in: textView.text) else {
return false
}
testString = textView.text.replacingCharacters(in: newRange, with: text)
return true
}
}
Update 2: After talking with Martin, I found and provided one detail that this problem only happens with the Google keyboard, and with the default keyboard everything works as expected.
The original line I had was "( ͡° ͜ʖ ͡°)༼ つ ͡° ͜ʖ ͡° ༽つ”
, this line is used for an example.If I start deleting this line from left to right, I get the app crash, Martin asked to show the latest data in the console before the app crashes, last print before crash is textView" "( ͡° ͜ʖ ͡°)༼ つ ͡° ͜ʖ ͡" "range" {27, 1}