Shark Deng

Interactive Designer @Shanju Design in Shanghai

touched caffe / mxnet / python / wordpress / bootstrap / Arduino / Raspberry Pi / webgl / three.js / PIXI / 3dMax

Email

Github

OC – UITextField常用操作

2019-11-19 03:50:50

一)监控用户输入内容后,登录按钮才可用

//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];

 

 

 



——By SharkDeng
如果你喜欢我的文章,欢迎红包赞赏

Leave a Reply

Your email address will not be published. Required fields are marked *