shouldChangeCharactersInRange gives different range with emoji

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?

Upvotes: 0

Views: 599

Answers (1)

ramchandra n
ramchandra n

Reputation: 2027

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

Upvotes: 1

Related Questions