UITextField —— 键盘弹出视图上移

来源:互联网 发布:潜韵耳机的官方淘宝店 编辑:程序博客网 时间:2024/04/29 03:44

实现原理: 坐标系转换后计算尺寸进行调整其偏移量

1 .定义全局变量

@property (nonatomic, strong) UITextField *currentTextfield;

2 . 在viewllWillAppear中设置监听

    [[NSNotificationCenter defaultCenter] addObserver:self                                             selector:@selector(keyboardWillShow:)                                                 name:UIKeyboardWillShowNotification                                               object:nil];    [[NSNotificationCenter defaultCenter] addObserver:self                                             selector:@selector(keyboardWillHide:)                                                 name:UIKeyboardWillHideNotification                                               object:nil];

3 .viewWillDisappear中设置移除监听

 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];

4 . 实现监听方法

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {    self.currentTextfield = textField;    return YES;}- (BOOL)textFieldShouldReturn:(UITextField *)textField  {    [textField resignFirstResponder];    return YES;}- (void)keyboardWillShow:(NSNotification *)notif {    CGRect rect = [[notif.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];    CGFloat keyBoardHeight = rect.size.heightUIWindow *currentWindow = [[UIApplication sharedApplication].delegate window];    CGRect actuRect = [self.currentTextfield convertRect:self.currentTextfield.bounds toView:currentWindow];    CGFloat maxY = currentWindow.frame.size.height - keyBoardHeight;    CGFloat actuY = CGRectGetMaxY(actuRect);    CGFloat currentOffset = self.view.transform.ty;    CGFloat needsOffset = maxY - actuY;     // 实际需要移动的偏移量    [UIView animateWithDuration:.35 animations:^{        if (needsOffset < fabs(currentOffset)) {  // 偏移量负的可直接上移,如果为正就需要考虑是否超过当前最多偏移量,如果超过则需要将其还原            self.view.transform = CGAffineTransformTranslate(self.view.transform, 0, needsOffset);        } else {            self.view.transform = CGAffineTransformIdentity;        }    }];}- (void)keyboardWillHide:(NSNotification *)notif {    [UIView animateWithDuration:.35 animations:^{        self.view.transform = CGAffineTransformIdentity;    }];    self.currentTextfield = nil;}

拓展: 如果想将所有的textField都实现这个功能便可以将其写在基类控制器中,这样让其他控制器继承自这个基类便可以了。如果想实现UITextView也可以用这种方式。原理不变。

0 0
原创粉丝点击