文本控件之UITextField

UITextField控件在登录注册这类填表的页面中常常用到,这里讨论采用的几个体验点

键盘的收起

scrollView滚动时收起键盘
非textField区域被点击时收起键盘

第一个属于滚动处理

_scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;

第二个属于点击处理

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTableViewTapped)];
[_scrollView addGestureRecognizer:tapRecognizer];

- (void)onTableViewTapped
{
    [_idCardNameField resignFirstResponder];
    [_idCardNumberField resignFirstResponder];
    [_mobilePhoneNumberField resignFirstResponder];
    [_mobileVerifyCodeField resignFirstResponder];
}

键盘的Return链

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([_idCardNameField isFirstResponder]) {
        [_idCardNumberField becomeFirstResponder];
    }
    else if([_idCardNumberField isFirstResponder]) {
        [_mobilePhoneNumberField becomeFirstResponder];
    }
    else if([_mobilePhoneNumberField isFirstResponder]) {
        [_mobileVerifyCodeField becomeFirstResponder];
    }
    else if ([_mobileVerifyCodeField isFirstResponder]) {
        [_mobileVerifyCodeField resignFirstResponder];
    }
    
    return YES;
}

键盘的定位

#pragma mark - Keyboard
- (void)keyboardDidShow:(NSNotification *)notification
{
    NSDictionary* info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGFloat kbHeight = kbSize.height + 45;//悬浮bar的高度
    
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(_scrollView.contentInset.top, 0.0, kbHeight, 0.0);
    _scrollView.contentInset = contentInsets;
    _scrollView.scrollIndicatorInsets = contentInsets;
    
    UITextField *firstResponderTextField = nil;
    if ([_idCardNameField isFirstResponder]) {
        firstResponderTextField = _idCardNameField;
    }
    else if ([_idCardNumberField isFirstResponder]) {
        firstResponderTextField = _idCardNumberField;
    }
    else if ([_mobilePhoneNumberField isFirstResponder]) {
        firstResponderTextField = _mobilePhoneNumberField;
    }
    else if ([_mobileVerifyCodeField isFirstResponder]) {
        firstResponderTextField = _mobileVerifyCodeField;
    }
    
    if (firstResponderTextField) {
        CGRect editItemRect = [_scrollView convertRect:firstResponderTextField.bounds fromView:firstResponderTextField];
        
        if (!CGRectIsNull(editItemRect)) {
            editItemRect.size.height += 40;
            [_scrollView scrollRectToVisible:editItemRect animated:YES];
        }
    }
}

- (void)keyboardDidHide:(NSNotification*)notification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(_scrollView.contentInset.top, 0, 0, 0);
    _scrollView.contentInset = contentInsets;
    _scrollView.scrollIndicatorInsets = contentInsets;
}

你可能感兴趣的:(文本控件之UITextField)