深入理解iOS API系列(一) textField:shouldChangeCharactersInRange:replacementString:

    前言

    深入理解iOS API系列是一个较深解读iOS API的博文集,限于时间和作者精力,内容并不会全部原创,但是涵盖的内容,应该是广大iOS开发者,特别是初中级开发者经常误解或理解不够深刻的部分。


主要是深入理解代理方法textField:shouldChangeCharactersInRange:replacementString:的使用。

转自http://www.cnblogs.com/Clin/p/3413146.html


如果要限制UITextField输入长度最长不超过kMaxLength,那么需要实现做以下操作:

1、实现UITextFieldDelegate协议;

2、实现textField:shouldChangeCharactersInRange:replacementString:方法;

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{

    NSInteger strLength = textField.text.length - range.length + string.length;

    return (strLength <= kMaxLength);

}

 

方法- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

功能:

  把textField中位置为range的字符串替换为string字符串;

  此函数在textField内容被修改时调用;

返回值:

  YES,表示修改生效;NO,表示不做修改,textField的内容不变。

参数说明:

  textField:响应UITextFieldDelegate协议的UITextField控件。

  range:    UITextField控件中光标选中的字符串,即被替换的字符串;

          range.length为0时,表示在位置range.location插入string。

  string:    替换字符串;

          string.length为0时,表示删除。


另外:http://www.tuicool.com/articles/yyQRnq

iOS6下UITextField退格变清空问题的解决方法

猜你喜欢

转载自blog.csdn.net/ximiaoweilai/article/details/51133619