How does the methods “shouldChangeTextInRange” and “stringByReplacingCharactersInRange” work?

大憨熊 提交于 2020-01-01 14:27:17

问题


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 number of characters that can be entered in the textField?

Thanks in advance!


回答1:


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.



来源:https://stackoverflow.com/questions/7554340/how-does-the-methods-shouldchangetextinrange-and-stringbyreplacingcharactersi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!