一)监控用户输入内容后,登录按钮才可用
//initial state
_btnSend.userInteractionEnabled = NO;
_btnSend.alpha = 0.5;
//login btn become enabled when user input value in textField
[NSNotificationCenter.defaultCenter addObserverForName:UITextFieldTextDidChangeNotification object:self.txtMsg queue:nil usingBlock:^(NSNotification * _Nonnull note) {
if (_txtMsg.text.length > 0) {
self.btnSend.userInteractionEnabled = YES;
self.btnSend.alpha = 1.0;
} else {
self.btnSend.userInteractionEnabled = NO;
self.btnSend.alpha = 0.5;
}
}];
二)定义uitextField,按return键或空白处退出键盘
打开UITextFieldDelegate
//click return
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
NSLog(@"return!!!!");
[textField resignFirstResponder];
return YES;
}
_txtMsg.delegate = self;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap:)];
[self.view addGestureRecognizer:tap];
- (void)handleTap: (UITapGestureRecognizer *)sender {
NSLog(@"oojoj");
[_txtMsg endEditing:true];
[_txtMsg resignFirstResponder];
}
三)观察手机号码
//observer value
//phone
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField.text.length >= 11) {
//range.length: cursor's length
//range.location: cursor's current location
//NSLog(@"length: %d,location: %d", range.length, range.location);
BOOL isMobileNum = [self isMobile:textField.text];
NSLog(@"%i", isMobileNum);
return NO; //will now show
} else {
return YES; //show in textField
}
}
- (BOOL) isMobile: (NSString *)sample {
NSString * mobile = @"^((13[0-9])|(14[^4,\\D])|(15[^4,\\D])|(18[0-9]))\\d{8}$|^1(7[0-9])\\d{8}$";
//Important: Use a %@ format specifier only to represent an expression. Do not use it to represent an entire predicate.
//If you attempt to use a format specifier to represent an entire predicate, the system raises an exception.
//NSPredicate *p = [NSPredicate predicateWithFormat:@"%@", mobile];
NSPredicate *p = [NSPredicate predicateWithFormat:@"self matches %@", mobile];
if ([p evaluateWithObject:sample] == YES ) {
return YES;
} else {
return NO;
}
}
四)关闭联想和大写
//关闭自动联想
[_txtMsg setAutocorrectionType:UITextAutocorrectionTypeNo];
//关闭大写
[_txtMsg setAutocapitalizationType:UITextAutocapitalizationTypeNone];