gpt4 book ai didi

ios - 出现键盘时如何在可见框架的中心移动 View ?

转载 作者:行者123 更新时间:2023-11-28 21:42:15 26 4
gpt4 key购买 nike

我在根 ScrollView 中嵌入了一个标准的 UIView(包含一个 ImageView 、两个文本字段和一个按钮)。我正在使用 AutoLayout 将 UIView 放在 ScrollView 的中心,如下面的屏幕截图所示。

Login Screenshot

我正在尝试编写一种方法,在键盘出现时将 UIView 向上移动,以便此 View 将出现在较小的可见框架的中心。为此,我计算了一些高度。

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

[UIView animateWithDuration:0.3 animations:^{
// Gets the root 'UIView' frame and stores it in a variable
CGRect viewFrame = self.itemsView.frame;
// This is the height of the visible frame once the keyboard appears
double visibleFrameHeight = (self.view.frame.size.height - keyboardSize.height);
// How much the 'UIView' should move up
double offset = ((visibleFrameHeight - viewFrame.size.height / 2);
// Moves up the 'UIView'
viewFrame.origin.y = -offset;
self.itemsView.frame = viewFrame;
}];
}

问题是 UIView 移得太高了,如下所示。

Login Screenshot with keyboard on screen

为什么会发生这种情况,我该如何解决?

最佳答案

如果您的 View 已经嵌入到 UIScrollView 中,那么您只需调整 ScrollView 的 contentOffset 即可移动 View (这样您就可以免费获得动画)。

假设 ScrollView 在名为 scrollView 的 socket 上可用,并且您希望保持 View 居中,您可以将内容偏移量移动键盘高度的 1/2。此外 - 使用 UIKeyboardFrameEndUserInfoKey 获取键盘的最终帧可能更安全:

- (void)keyboardWillShow:(NSNotification *)notification {
// Determines the size of the keyboard frame
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
self.scrollView.contentOffset = CGPointMake(0, keyboardSize.height / 2);
}

- (void)keyboardWillHide:(NSNotification *)notification {
self.scrollView.contentOffset = CGPointZero;
}

关于ios - 出现键盘时如何在可见框架的中心移动 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31560406/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com