我有一个简单的 UIScrollView
与 2 UITextField
里面有一段代码,对我来说没有任何意义,但它正在工作。
这是屏幕(我正在使用自动布局):
代码如下:
- (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];
}
- (void)keyboardWillShow:(NSNotification*) notif
{
NSDictionary *info = [notif userInfo];
CGRect keyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
UIEdgeInsets contentInset = self.scrollView.contentInset;
contentInset.bottom = keyboardRect.size.height;
self.scrollView.contentInset = contentInset;
}
- (void) keyboardWillHide:(NSNotification*) notif
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
_scrollView.contentInset = contentInsets;
}
我希望将 ScrollView 向上移动 352 点(键盘的高度),因为这是我设置的值 contentInset.bottom
去,哪个都不重要UITextField
被选中,因为键盘的高度始终相同。
但是结果是向上滚动,所以 UITextField
即第一响应者不会被键盘覆盖。所以它在底部的情况下滚动得更多 UITextField
如果是顶级的,则更少。这看起来当然比我预期的结果要好得多,但我不明白为什么它会起作用。谁有解释?
最佳答案
发生这种情况的原因是更改内容插图只会更改插图,它实际上不会更改 ScrollView 的 contentOffset。
请参阅有关滚动键盘 View 的 SO 帖子:How do I scroll the UIScrollView when the keyboard appears?
从那篇文章中,我认为您需要最后的部分来向上 ScrollView 以显示两个字段:
// If active text field is hidden by keyboard, scroll it so it's visible
// Your application might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y-kbSize.height);
[scrollView setContentOffset:scrollPoint animated:YES];
}
关于ios - UIScrollview 中的 UITextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25915375/