开发者

How does the methods "shouldChangeTextInRange" and "stringByReplacingCharactersInRange" work?

开发者 https://www.devze.com 2023-04-08 22:55 出处:网络
I would like to know the working of the following code. - (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号