iOS UITextField相关

 1. 隐藏键盘

//触摸self.view隐藏
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

//滚动UITableView隐藏
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

2. new个field

#pragma mark - Getter

- (UITextField *)fieldAccount {
    if (!_fieldAccount) {
        _fieldAccount = [UITextField newAutoLayoutView];
        _fieldAccount.delegate = self;
        
        //提示文字颜色
        _fieldAccount.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入手机号码" attributes:@{NSForegroundColorAttributeName:kColor(0x888888)}];
        
        _fieldAccount.clearButtonMode = UITextFieldViewModeWhileEditing;
        _fieldAccount.keyboardType = UIKeyboardTypePhonePad;
        _fieldAccount.returnKeyType = UIReturnKeyNext;
        
        _fieldAccount.font = kFontCNSize(12);
        _fieldAccount.tintColor = kColorRed;
        
        _fieldAccount.textColor = [UIColor whiteColor];
        _fieldAccount.textAlignment = NSTextAlignmentCenter;

        [self.view addSubview:_fieldAccount];
    }
    
    return _fieldAccount;
}

3. textField代理 限制输入长度

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSInteger len = 30;

    //手机号11位数字
    if (self.fieldAccount == textField) {
        len = 11;
    } else if (self.fieldPassword == textField) {
        len = 16;
    }

    NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (toBeString.length > len && range.length!=1) {
        textField.text = [toBeString substringToIndex:len];

        return NO;
    }

    if (self.fieldAccount == textField) {
        return [self validateNumber:string];
    }

    return YES;
}

- (BOOL)validateNumber:(NSString*)number {
    NSCharacterSet *tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString *string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            return NO;
        }

        i++;
    }

    return YES;
}

//或者
- (BOOL)validateNumber:(NSString*)number field:(UITextField *)field{
    NSCharacterSet *tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789+*#"];
    int i = 0;
    while (i < number.length) {
        NSString *string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            field.text = (number.length == 1)?@"":[number substringToIndex:i];
            return NO;
        }
        i++;
    }
    
    return YES;
}

4. 

5. 

你可能感兴趣的:(ios,UITextField)