If I implement the method shouldChangeCharactersInRange
there is some kind of inconsistency between the value on range and the text size.
When I have the textfield with only one common letter (like "a") and press backspace the text to be replaced is an empty string, textField.text!.characters.count
returns 1 and the rage has position 0 and length 1 (which everything makes sense), however if the text field has just a emoji (like ""), range.length
returns 2 rather than 1, and then I have a crash when casting range from NSRange
to Range<String.Index>
. Why does it happen?
Asked
Active
Viewed 565 times
0

Hola Soy Edu Feliz Navidad
- 6,746
- 4
- 38
- 55
-
Possible duplicate of [NSRange to Range
](http://stackoverflow.com/questions/25138339/nsrange-to-rangestring-index) – String and NSString ranges are different, and you cannot simply "cast" between them. – Martin R Nov 22 '16 at 14:48
1 Answers
1
Swift 3.0+
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let strtext = textField.text else {
return true }
let completeString = (strtext as NSString).replacingCharacters(in: range, with: string)
let increment = string == "" ? 0 : 1
let finalString = (completeString as NSString).substring(with: NSRange(location: 0, length: range.location + increment))
print(finalString)
return true
}
Note: - This will gives the string with range startIndex to cursor position

ramchandra n
- 1,957
- 1
- 15
- 15