How does the methods "shouldChangeTextInRange" and "stringByReplacingCharactersInRange" work?
I would like to know the working of the following code.
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
return !([newString length] > 10);
}
What does "stringByReplacingCharactersInRange" do? And how does the above method limit the 开发者_Go百科number of characters that can be entered in the textField?
Thanks in advance!
textField:shouldChangeCharactersInRange:replacementString:
is UITextFieldDelegate method that gets called any time text field's contents are about to change (entering, deleting, cutting or pasting text into the text field), asking the delegate if it wants to allow this change.
stringByReplacingCharactersInRange:withString:
is an NSString instance method that does exactly what it says, replaces some text in current string with another string, creating a new string.
The code you have checks if the string that would be a result of this change is longer than 10 characters and if it is, delegate will return NO
and text field contents will not change. If the resulting string would be 10 characters or less, delegate will return YES
and text field's contents will change to the same string that you got in newString
.
精彩评论