出现键盘时向上移动 UIView [英] Move UIView up when keyboard appears

查看:29
本文介绍了出现键盘时向上移动 UIView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我已经完成了几乎所有关于 SO 和教程的问题.我现在可以将我的 UIView 向上移动,以便在键入时可以看到它.然而问题是,如果 UITextField 被键盘覆盖,我想移动 UIView ONLY ,因为如果它没有,那么有移动 UIView 没有意义.到目前为止我的代码:

Ok so I have gone through almost all questions on SO and tutorials. I am now able to move my UIView up so that it is visible while typing. However the problem is, I want to move the UIView ONLY if the UITextField gets covered by the keyboard, because if it is not, then there is no point in moving the UIView. My code so far:

- (void)viewDidLoad 
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self                                                selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];

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

#pragma mark - keyboard movements
- (void)keyboardWillShow:(NSNotification *)notification
{
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    [UIView animateWithDuration:0.3 animations:^{
        CGRect f = self.view.frame;
        f.origin.y = -keyboardSize.height;
        self.view.frame = f;
    }];
}

-(void)keyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect f = self.view.frame;
        f.origin.y = 0.0f;
        self.view.frame = f;
    }];
}

任何帮助将不胜感激,谢谢.

Any help will be appreciated, thank you.

推荐答案

要检查 UITextField 是否被键盘覆盖,您可以执行以下操作:

To check is UITextField covered by keyboard you can do something like this:

- (void)keyboardWillShow:(NSNotification *)notification {
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    if (myTextField.frame.origin.y + myTextField.frame.size.height > [UIScreen mainScreen].bounds.size.height - keyboardSize.height) {
        // textfield is covered by keyboard
        [UIView animateWithDuration:0.3 animations:^{
            CGRect f = self.view.frame;
            f.origin.y = -keyboardSize.height;
            self.view.frame = f;
        }];
    }
}

这篇关于出现键盘时向上移动 UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆