【问题标题】:How to scroll UITableView cell out of the way of the on-screen keyboad?如何将 TableView 单元格滚动到屏幕键盘之外?
【发布时间】:2011-06-18 15:02:44
【问题描述】:

这一定是一个常见问题...我在表格单元格中有一个UITextField,我想让用户编辑它。但是,当键盘出现时,它通常会遮盖文本字段。

我尝试过使用scrollToRowAtIndexPath:atScrollPosition,但令人惊讶的是这不起作用。我尝试将 UITableViewScrollPosition 设置为 {None,Top,Button,Middle}

我错过了滚动的秘诀是什么?

谢谢。

【问题讨论】:

    标签: ios uitableview uitextfield


    【解决方案1】:

    秘诀在于您必须手动实现该行为,这很痛苦。

    您必须采取几个步骤:

    第 1 步:注册键盘通知

    - (void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
    
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
    
    }
    

    第 2 步:在键盘出现时调整内容插入的大小

    - (void)keyboardWasShown:(NSNotification *)notification {
        NSDictionary* info = [notification userInfo];
        CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
        UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0f, 0.0f, kbSize.height, 0.0f);
        self.tableview.contentInset = contentInsets;
        self.tableview.scrollIndicatorInsets = contentInsets;
    
        [self.scrollView scrollRectToVisible:self.selectedView.frame animated:YES];
    }
    

    这假设您的类中有一个名为“selectedView”的属性。还有其他方法可以做到这一点,但主要是你需要知道用户需要看到什么视图矩形。

    第 3 步:在键盘消失时重置表格视图

    - (void)keyboardWillBeHidden:(NSNotification *)notification {
        UIEdgeInsets contentInsets = UIEdgeInsetsZero;
        self.tableview.contentInset = contentInsets;
        self.tableview.scrollIndicatorInsets = contentInsets;
    }
    

    第 4 步:取消注册通知

    - (void)viewWillDisappear:(BOOL)animated {
        [super viewWillDisappear:animated];
    
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    }
    

    【讨论】:

    • 谢谢。我试图在没有通知的情况下做类似的事情,但它当然不起作用。现在可以了。
    • @Starboo 不要使用硬编码值,它几乎肯定会在未来的 iOS 版本中中断。如果您的文本区域飞出屏幕,可能是因为您没有正确设置 selectedView,但没有更多代码,这只是猜测。
    【解决方案2】:

    那么,您的表格单元格是否隐藏了您的文本字段?为什么要通过滚动来解决它?更改将文本字段添加到单元格的方式。

    【讨论】:

    • 他的问题是如何避免文本字段被键盘隐藏
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    • 2017-03-10
    • 2020-08-06
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    相关资源
    最近更新 更多