- (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 below method
- (BOOL)textFieldShouldClear:(UITextField *)textField
The behavior you are seeing does not depend on
textFieldShouldClear:, whose default implementation already returns YES (source):The problem lays with
textField:shouldChangeCharactersInRange:denying any change whenever the textField contains more that 8 characters: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
replacementStringand 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 intextField:shouldChangeCharactersInRange:, you return YES.