I have a viewController
where I can enter some text into a textField
and tap a done button
to save it. I only want the done button to be visible if there is text in the textField. In order to do this, I used the delegate method for the UITexfield
which fires when it is about to be edited as shown below. As it passes in an NSRange
, I can't put that into stringByReplacingCharactersInRange
as swift only allows a Range. Therefor I bridged it which allowed me to use the NSRange
given. If you know a way to cast an NSRange
as a Range, or even better, if you know a more concise and neater way to check if the text field is empty, please let me know. Thanks a lot.
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
let newString = textField.text.bridgeToObjectiveC().stringByReplacingCharactersInRange(range, withString: string)
if (newString == "" ) {
self.doneButton.enabled = false
} else {
self.doneButton.enabled = true
}
return true
}