繁体   English   中英

使用UIScrollview将UIToolBar移动到屏幕上键盘上方

[英]Move UIToolBar above keyboard on screen with UIScrollview

我在iPhone应用程序中有一个包含UITextView的屏幕。 此文本视图包含在UIScrollView中。 屏幕的目的是使用户键入文本,并有选择地将图像附加到他所写的内容上。 因此,该屏幕还具有UIToolbar,该UIToolbar在屏幕底部带有一个摄像头按钮。 屏幕的结构如下:

-View
--UIScrollView
---UITextView
--UIToolbar
---UIButton

当用户导航到此屏幕时,viewDidAppear方法将第一响应者分配给uitextview元素,因此显示了键盘,该键盘隐藏了工具栏和相机按钮。

我希望整个工具栏在键盘上方重新绘制自己,并在键盘隐藏时再次将其自身放置在屏幕底部。

我在SO上找到了相关的帖子(像这样 )。 但是,这样的方法引入了不希望的行为。 例如,实现上述文章中的解决方案后,工具栏确实会随着键盘移动,但是UIScrollView的frame.origin.y坐标在屏幕上方移动了,因此用户无法看到他在做什么。打字。

我还尝试过通过将其添加为IBOutlet并使用cgrectmake重新定位来重置工具栏的框架。 但是,经过几次尝试,工具栏仍停留在屏幕底部,并被键盘隐藏:

- (void) liftMainViewWhenKeybordAppears:(NSNotification*)aNotification{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationCurve:<#(UIViewAnimationCurve)#>]

    CGRect frame = self.keyboardToolbar.frame;
    frame.origin.y = self.keyboardToolbar.frame.origin.y - 280;
    self.keyboardToolbar.frame = frame;

    [UIView commitAnimations];
}

我尝试了几次与上面的代码相似的迭代,但是它们都无法重新定位工具栏。

简而言之,将工具栏浮动在uitextview元素完全利用其屏幕的屏幕上方的键盘上方的正确方法是什么?

感谢RoryMcKinnel提供的指针。 正如所引用的文章是在Swift中一样,我认为我可以粘贴对ObjC起作用的解决方案

- (void)keyboardWillShowNotification:(NSNotification *)notification{
NSDictionary *userInfo = notification.userInfo;

double animationDuration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect keyboardEndFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGRect convertedKeyboardFrame = [self.view convertRect:keyboardEndFrame fromView:self.view.window];
UIViewAnimationOptions rawAnimationCurve = (UIViewAnimationOptions)[userInfo[UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue] << 16;
_toolBarBottomGuide.constant = CGRectGetMaxY(self.view.bounds) - CGRectGetMinY(convertedKeyboardFrame);
[UIView animateWithDuration:animationDuration delay:0.0 options:rawAnimationCurve animations:^{
    [self.view layoutIfNeeded];
} completion:nil];
}

请记住,此代码确实使工具栏按要求移动,但是该工具栏根本不可见。 原来,它被隐藏在UIScrollView的后面。 通过在IB层次结构中的滚动视图和工具栏元素之间移动顺序,可以轻松解决此问题。

上面的方法适用于keyboardWillShow事件。 键盘隐藏时,您需要添加相应的键盘,如下所示:

- (void)keyboardWillHideNotification:(NSNotification *)notification{
    NSDictionary *userInfo = notification.userInfo;

    double animationDuration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect keyboardEndFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    UIViewAnimationOptions rawAnimationCurve = (UIViewAnimationOptions)[userInfo[UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue] << 16;
    _toolBarBottomGuide.constant = 0.0f;
    [UIView animateWithDuration:animationDuration delay:0.0 options:rawAnimationCurve animations:^{
        [self.view layoutIfNeeded];
    } completion:nil];
}

暂无
暂无

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

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