ios - UIScrollview 中的 UITextField

标签 ios uiscrollview

我有一个简单的 UIScrollView与 2 UITextField里面有一段代码,对我来说没有任何意义,但它正在工作。

这是屏幕(我正在使用自动布局):

Here is the screen in the storyboard

代码如下:

- (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如果是顶级的,则更少。这看起来当然比我预期的结果要好得多,但我不明白为什么它会起作用。谁有解释?

enter image description here

enter image description here

最佳答案

发生这种情况的原因是更改内容插图只会更改插图,它实际上不会更改 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/

相关文章:

android - Xamarin 用户指南

ios - UIAlertView 中变量的占位符?

swift - UITextField 打开时被键盘部分隐藏

IOS/objective-C : Detect Textfield touch but Exclude tap of underlying scrollview

swift - UIScrollView contentOffset 在点击时重置

ios - 在 iOS 中将项目放置在屏幕中央

ios - Segue 不执行 iOS8

ios - 我怎么知道 viewcontroller 是因为推送加载还是因为 UINavigationController 弹出后的 View 重建加载?

ios - 在 ScrollView 的 ContentView 中拉伸(stretch) UIView

ios - UIScrollView 添加顶部空白