方法"shouldChangeTextInRange"如何进行?和"stringByReplacingCharactersInRange"工作? [英] How does the methods "shouldChangeTextInRange" and "stringByReplacingCharactersInRange" work?

查看:76
本文介绍了方法"shouldChangeTextInRange"如何进行?和"stringByReplacingCharactersInRange"工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道以下代码的工作原理.

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);
}

"stringByReplacingCharactersInRange"是做什么的?以及上述方法如何限制可以在textField中输入的字符数?

What does "stringByReplacingCharactersInRange" do? And how does the above method limit the number of characters that can be entered in the textField?

提前谢谢!

推荐答案

textField:shouldChangeCharactersInRange:replacementString:

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:是一个NSString实例方法,它完全按照其说的去做,用另一个字符串替换当前字符串中的某些文本,从而创建一个新字符串.

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.

您拥有的代码将检查由于此更改而导致的字符串是否超过10个字符,如果是,则委托将返回 NO ,并且文本字段内容不会更改.如果结果字符串为10个字符或更少,则委托将返回 YES ,并且文本字段的内容将更改为您在 newString 中获得的字符串.

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.

这篇关于方法"shouldChangeTextInRange"如何进行?和"stringByReplacingCharactersInRange"工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆