how to clear the text field by using the delegate functions
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField.text.length >=8)
{
return NO; // return NO to not change text
}
else {
return YES;
}
}
when i am adding this method to my program, text will not be clear. how can i clear my text field. by using the 开发者_如何学JAVAbelow method
- (BOOL)textFieldShouldClear:(UITextField *)textField
The behavior you are seeing does not depend on textFieldShouldClear:
, whose default implementation already returns YES (source):
The text field calls this method in response to the user pressing the built-in clear button. (This button is not shown by default but can be enabled by changing the value in the clearButtonMode property of the text field.) This method is also called when editing begins and the clearsOnBeginEditing property of the text field is set to YES.
The problem lays with textField:shouldChangeCharactersInRange:
denying any change whenever the textField contains more that 8 characters:
if (textField.text.length >=8) {
return NO; // return NO to not change text
I don't know why you set this or if you could find another way to get the same, but if you want to leave it like this, then a possible workaround is checking the replacementString
and if it is empty, allow the text change by returning YES.
If you want a more sophisticated solution, you could think of setting an ivar flag when textFieldShouldClear:
is called, so that when you find the flag set in textField:shouldChangeCharactersInRange:
, you return YES.
- (BOOL)textFieldShouldClear:(UITextField *)textField {
self.shouldClearTextCalled = YES;
return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (self.shouldClearTextCalled)
return YES;
self.shouldClearTextCalled = NO;
if (textField.text.length >=8) {
return NO; // return NO to not change text
} else {
return YES;
}
}
精彩评论