iosipaduitextfieldswift4.2undo-redo

UITextField crash undo keyboard icon


Facing this error in iPad app. In textfield keyboard will appear. write any text like "qwertyuio" then copy and paste this text multiple times until limit reached out. Now, press undo from the keyboard application will be crashed. I have tried to search out but unable to find any solution. Exception: "Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray replaceObjectsInRange:withObject:length:: Out of bounds'"

Code, I am using:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, 
 replacementString string: String) -> Bool {
   if textField.text?.count >= 40 && string != ""{
                
      return false
                
   }
  return true
}

Please provide the solution. thanks


Solution

  • After digging out couple of hours. I found the solution for this one.

       var textSize = 0
                
       if range.length == 0 {
          //adding
          textSize = range.location + string.count
       }else{
           //removing from field
           textSize = range.location - range.length
        }
                
        if textSize >= 50 {
    
           return false
    
        }else {
           if (string.isEmpty && range.length > 0) {
           textField.text = textField.text!.count > range.length ? String(textField.text!.dropLast(range.length)) : ""
           return false
        }
    

    It is working fine now.