一、前言
今天做手機號輸入限制長度,例如我的textfield只能輸入11位,如果再多輸入的話就不再textfield中顯示,只顯示11位的手機號。
如果用ReactiveCocoa的話,這個很好解決。但是項目中沒有引入該類庫,所以只能手動的取完成了。
二、實現原理
先看代碼:
// // ViewController.m // Test // // Created by zhanggui on 15/12/28. // Copyright © 2015年 zhanggui. All rights reserved. // #import "ViewController.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UITextField *myTextField; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledEditChanged:) name:@"UITextFieldTextDidChangeNotification" object:self.myTextField]; self.myTextField.placeholder = @"只能輸入11位哦"; // Do any additional setup after loading the view, typically from a nib. } #pragma mark - UITextFieldDelegate -(void)textFiledEditChanged:(NSNotification *)obj{ UITextField *textField = (UITextField *)obj.object; NSString *toBeString = textField.text; if (toBeString.length-1 > 10 && toBeString.length>1) { textField.text = [toBeString substringToIndex:11]; } } @end
做法如下:
首先,我們需要添加一個通知,這個通知的name是:UITextFieldTextDidChangeNotification 。我們可以點擊這個名字進去,會發現
UIKIT_EXTERN NSString *const UITextFieldTextDidChangeNotification;
這個是在UITextField.h中定義的一個常量字符串,他的作用如下:
通知觀察者textField中的內容改變了,受影響的textField就存儲在通知的object參數中。(Notifies observers that the text in a text field changed. The affected text field is stored in the object parameter of the notification.)
這樣的話,我們就可以通過通知來控制了。當我們每次輸入字符到textField中的時候,都會在通知的方法中進行監聽,我就在里面判斷輸入的字符串的長度是否滿足需要的條件,如果滿足了條件(我這里的條件是11位),就讓textField的text始終等於我要限制的長度。以此來完成自己的需求。
=========== =========== =========== =========== =========== =========== ===========
2015年12月31日下午5:57更新
另一個簡單的方法:代碼如下:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; if ([toBeString length] > 11) { textField.text = [toBeString substringToIndex:11]; return NO; } return YES; }