键盘

时间:2016-06-20 12:57:26

标签: ios objective-c uiscrollview keyboard uitextfield

我有一个带有UIView的UIScrollView,基于一篇文章如何将autolayout与输入字段一起使用。本文解释了如何将UIView设置为与普通视图相同的高度,以获取更多信息:https://www.natashatherobot.com/ios-autolayout-scrollview/

现在我的内容视图中有多个UITextField。当我按下UITextField时,我希望我的视图显示键盘并滚动到UITextField。起初,我尝试了多个使用的方法,但问题是,在屏幕的底部,我从视图底部获得了大量空白空间,这是不需要的。我尝试的方法是使用以下几行:

- (void)keyboardWillHide:(NSNotification *)notification {
    [[self scrollView] setContentInset:UIEdgeInsetsMake([[self scrollView] contentInset].top, 0.0f, 0.0f, 0.0f)];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    [[self scrollView] setContentInset:UIEdgeInsetsMake([[self scrollView] contentInset].top, 0.0f, [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height, 0.0f)];
}

要改变这一点,我认为将底部更改为更合适的值可以解决问题,但是当我这样做时,当我按下它时,视图不再滚动到UITextField。我可以手动滚动字段。我实现这一目标的方法是使用以下内容:

- (void)keyboardWillShow:(NSNotification *)notification {
    float keyboard = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    float offset = [[[[self contentView] subviews] lastObject] frame].size.height + [[[[self contentView] subviews] lastObject] frame].origin.y + 30.0f;

    if ([[self contentView] frame].size.height - [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height < offset) {
        [[self scrollView] setContentInset:UIEdgeInsetsMake([[self scrollView] contentInset].top, 0.0f, offset - ([[self view] frame].size.height - keyboard), 0.0f)];
    }
}

有人知道滚动时如何忽略UITextFields下的空白区域,但允许滚动视图滚动到选定的UITextField。我尝试使用scrollRectToVisible方法,但这并没有做任何事情。

1 个答案:

答案 0 :(得分:0)

我发现上述答案已经过时了。滚动时也不完美。

这是一个快速版本。

它将在textField下方滚动,没有空余空间。它将恢复到它第一次出现的样式。

Quote {0.0.0.0} XXX <1>A<2>B<3>C