Check if a UITextField is empty

Can someone please explain this code a little bit in more details?

I don’t understand how the range and replaceCharachters method work here, when we get the oldText and get the range in this text isn’t it supposed to be the range of the whole string so when we use the oldText.replacingCharacters method it should replace the whole text with the string parameter from the UITextField delegate method and get assigned to the new newText, but when I printed it the string it is just a character.

this is what I think should happen but I know it’s wrong but I can’t figure how these lines work.

let oldText = textField.text!    
  let stringRange = Range(range, in: oldText)!
  let newText = oldText.replacingCharacters(
    in: stringRange, 
    with: string)
  if newText.isEmpty {
    doneBarButton.isEnabled = false
  } else {
    doneBarButton.isEnabled = true
  }
  return true
}

@ahmednagy The string parameter of the textField(_:shouldChangeCharactersIn:replacementString:) method contains only the characters that are changed in the textfield’s text in this case so you only need to replace that part of the original text because of that.

The range parameter of the textField(_:shouldChangeCharactersIn:replacementString:) method determines the position of the old characters in oldText. This is also the position of the new characters in newText, so the replacingCharacters(in:with:) method replaces the range of characters in oldText with string in this case.

You can read even more about the textField(_:shouldChangeCharactersIn:replacementString:) method over here:

https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619599-textfield

Please let me know if you have any other questions or more issues about the whole thing when you get a chance. Thank you!

sorry i can’t wrap my head around it the problem is when i print the “string” paramenter it gives me just one charachter so replacingCharacters(in:with:) should replace the whole charachters passed to the “in” parameter with the “string” parameter which is one letter.

pardon my english i will try to explain how i think this code works so
first if i typed “a” then oldText would be equal to the char “a” then the stringRange should be equal to the whole range of my oldText so calling replacingCharacters(in:with:) with the “stringRange” and “string” as my arguments that should result replacing the whole range of oldtext which is the whole word with just the new character the user typed which is passed in the “string” parameter as i said when i print it it gives me one chatacter.

so what exactly am i missing here?

This topic was automatically closed after 166 days. New replies are no longer allowed.