IPhone Objective-C only enable a button if NSTextfield is not blank
I have a button that I only want enabled when a textfield is not blank. I have been trying to do this by implementing the following method, without any luck.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
Is there another delegate method that I could implement that gets fired after the text is changed? In this method is there some way to tell what ke开发者_如何学Goy is being pressed, if it's a delete or something like that?
You can just check for string.length == 0
and range.length > 0;
. This denotes a deletion. However, what you really want is to just do the pending modification and then check that you still have a non-empty string.
Something like this (typed in, not compiled):
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *testString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if( testString.length )
myButton.enabled = YES;
else
myButton.enabled = NO;
return YES;
}
精彩评论