美文网首页
UITextField汇总

UITextField汇总

作者: ChrisF1030 | 来源:发表于2016-01-14 13:44 被阅读191次

UITextField 虽然不是复杂的控件,但因为很多功能不熟悉的缘故,每次还是会浪费很多时间去实现想要的功能,下面对常用的方法进行一下汇总:

1、对输入内容的监听
通过监听 UIControlEventEditingChanged 状态,实现对输入的内容的处理,常用于限制输入位数、限制输入内容等。

{
    [self.passwordTextField addTarget:self action:@selector(textFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
    [self.repeatTextField addTarget:self action:@selector(textFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
}

- (void)textFieldDidChanged:(UITextField *)textField
{
    if (textField.text.length > 11) {
        
        textField.text = [textField.text substringToIndex:11];
        
    }
}

2、处理键盘弹出、收回事件。

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self keyboardAnimate:textField show:YES];
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self keyboardAnimate:textField show:NO];
}
- (void)keyboardAnimate:(UITextField *)textField show:(BOOL)willShow
{

    CGFloat dist = self.backgroundView.frame.origin.y + [textField superview].frame.origin.y + textField.frame.origin.y + textField.frame.size.height - (self.backgroundView.frame.size.height - 216.0);
    
    CGFloat offset = (willShow ? - dist : 0);
    
    // 键盘弹出时,若dist为负,则不需要上移_backgroudView
    if (willShow) {
        
        if (dist < 0) {
            
            offset = 0;
            
        }
    }

    _backgroudViewTop.constant = offset;

    [UIView animateWithDuration:0.25f animations:^{
        
        [self.view layoutIfNeeded];
        
    }];
 
}

注意:坐标原点在左上角、textFiled父视图坐标。

思路

  • 键盘弹出时,需要计算合适的视图上移距离 offset,计算公式:

offset = textFiled 底部y - ( backgroundView.height - keyboard.height );

上面的例子中将 keyboard.height 直接设为216.0,可监听键盘事件, 获取当前键盘高度,更为准确。

  • 修改背景视图的frame,对整个视图进行上移。
    另,当父视图或textFiled存在autoLayout关系时,需要更改对应的约束值,然后刷新autoLayout。
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *backgroudViewTop;
_backgroudViewTop.constant = offset;
    [UIView animateWithDuration:0.25f animations:^{
        
        [self.view layoutIfNeeded];
        
    }];

参考:【iOS】Autolayout动画之键盘弹出

相关文章

网友评论

      本文标题:UITextField汇总

      本文链接:https://www.haomeiwen.com/subject/krthkttx.html