繁体   English   中英

当用户单击文本字段时,将UITextField移到键盘上方

[英]Move UITextField above keyboard when user click on textfield

当用户单击UITextField时,我想将UITextField向上移动到键盘上方。

我搜索了一下,一些建议是将整个视图向上移动,有些建议是添加scrollview。

但是我不想使用scrollview。

我怎样才能做到这一点?

给你UITextField底部常数,当你发现在键盘高度keyboardWillShow增加你UITextField底部约束KeyboardHeight

只需将下面的代码放在ViewWillAppear中。

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

并将下面的代码放在ViewWillDisappear中。

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

方法

- (void)keyboardWillShow:(NSNotification *)notification
{
    // Get the size of the keyboard.
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    int keyboardHeight = MIN(keyboardSize.height,keyboardSize.width);

    textBottom.constant = 0.0f;

    for (UIView *vw in commentView.subviews) {
        if ([vw isKindOfClass:[UITextField class]]) {
            txtComment = (UITextField *)vw;
            textBottom.constant = keyboardHeight;
        }
    }
}

这是一个很棒的解决方案: https : //github.com/hackiftekhar/IQKeyboardManager

它易于集成且毫不费力。

您不必在每个UIViewControllers中都使用UIScrollView。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM