概述:
在開發中,為了與用戶進行溝通,一般都會有讓用戶輸入的東西,尤其是在登錄的時候,也必須要讓用戶輸入合乎規范的輸入內容,因此我特地在網上查了一下UITextField和UITextView的對輸入內容的限制,發現有一些限制是存在問題的,所以此文特地總結了一下正確的限制方法。
UITextField對輸入內容的限制
注意:UITextField最好使用添加方法的辦法來限制長度,如果使用代理的方法來限制長度,是比較麻煩的。使用通知的話性能會有所降低。
方法一:添加事件
//創建一個UITextField對象
UITextField *textFld = [[UITextField alloc] init];
//添加方法,一旦textField的內容改變就會調用設置的方法
[textFld addTarget:self action:@selector(textFldChange:) forControlEvents:UIControlEventEditingChanged];
-(void)textFldChange:(UITextField *)textFld{
//這里拿到的就是textFld上面的內容
NSLog(@"%@",textFld.text);
//限制長度為11位
if (textFld.text.length >= 11) {
textFld.text = [textFld.text substringWithRange:NSMakeRange(0, 11)];
}
}
方法二:發送通知
//創建一個UITextField對象
UITextField *textFld = [[UITextField alloc] init];
//添加通知,一旦textField的內容改變就會調用設置的方法
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFldChange:) name:UITextFieldTextDidChangeNotification object:textFld];
-(void)textFldChange:(NSNotification *)notification{
UITextField *textFld = (UITextField *)notification.object;
//這里拿到的就是textFld上面的內容
NSLog(@"%@",textFld.text);
//限制長度為11位
if (textFld.text.length >= 11) {
textFld.text = [textFld.text substringWithRange:NSMakeRange(0, 11)];
}
}
方法三:代理的方式
//創建一個UITextField對象
UITextField *textFld = [[UITextField alloc] init];
textFld.delegate = self;
#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if ([string isEqualToString:@""] && range.length > 0) {
//刪除字符
return YES;
}else{
if (textField.text.length + string.length > 11) {
return NO;
}else{
return YES;
}
}
}
UITextView對輸入內容的限制
注意:TextView是沒有辦法添加事件的,所有只能使用通知和代理的方法來限制TextView的內容長度。
方法一:發送通知
//創建一個UITextView對象
UITextView *textView = [[UITextView alloc] init];
//添加通知,一旦textView的內容改變就會調用設置的方法
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewChange:) name:UITextViewTextDidChangeNotification object:textView];
-(void)textViewChange:(NSNotification *)notification{
UITextView *textView = (UITextView *)notification.object;
//這里拿到的就是textView上面的內容
NSLog(@"%@",textView.text);
//限制長度為11位
if (textView.text.length >= 11) {
textView.text = [textView.text substringWithRange:NSMakeRange(0, 11)];
}
}
方法二:代理的方式
//創建一個UITextView對象
UITextView *textView = [[UITextView alloc] init];
textView.delegate = self;
#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
if ([text isEqualToString:@""] && range.length > 0) {
//刪除字符
return YES;
}else{
if (textView.text.length + text.length > 11) {
return NO;
}else{
return YES;
}
}
}
優化
textField.markedTextRange == nil
這個方法可以解決iOS中文輸入下的長度限制問題