【问题标题】:Scroll to UITableViewCell that contains a certain UITextField滚动到包含某个 UITextField 的 UITableViewCell
【发布时间】:2013-03-19 21:41:11
【问题描述】:

我有一个带有静态自定义UITableViewCells 的UITableView,我需要将一个文本字段滚动到视图中,因为当前它们在按下返回键并设置下一个响应者后隐藏在键盘后面。我知道我需要使用scrollToRowAtIndexPath:atScrollPosition:animated:。我将如何滚动到其中一个文本框?

我知道这应该自行滚动,但如果您的 UIViewController 派生自 UITableViewController(正如 Apple 所说的那样),那么 UITableViewController 类通过实现 UITextFieldDelegateUIScrollViewDelegate 等为您处理此行为。当我更改为从UIViewController 派生并将表视图添加到视图控制器的UIView 之上时,我的应用程序停止了此操作。所以基本上我错过了UITableViewController 的功能,因为我(出于其他原因)选择从UIViewControler 派生。

【问题讨论】:

    标签: ios objective-c uiviewcontroller uitableview


    【解决方案1】:

    我一直这样做。我这样做的方式是我有一个在 UIControlEventEditingDidBegin 中为文本字段调用的方法,在该方法中,我这样做:

    -(void)startEdit:(UITextField *)textField {
        self.prevOffset = self.tableView.contentOffset.y; //I like storing the current offset so I can restore it when the text stops editing, you don't have to do this.
        int offSet = [textField superview].frame.origin.y; //this gets the y coordinate of the cell the textField is in. If the table is not at 0,0, you also need to add [[textField superview] superview].frame.origin.y;
        offSet-=(self.view.frame.size.height-KEYBOARD_HEIGHT)/2; //where KEYBOARD_HEIGHT is 216 in portrait and 160 in landscape;
        if (offSet<0) offSet = 0;
        [UIView animateWithDuration:0.3 animations:^{
            [self.tableView setContentOffset:CGPointMake(0,offSet)];}];
    }
    

    我还做很多其他事情,但我相信它们是针对我的应用程序的。

    首先,如果偏移量大于 0,我将 contentInset 设置为 UIEdgeInsetsMake(0,0,KEYBOARD_HEIGHT,0),因为在此之前我有一些跳跃的滚动视图。

    另外,如果原始偏移量 (self.prevOffset) 加上框架的高度大于内容大小(这也会导致跳跃,因为它将偏移量设置得太低然后跳回来),我将 prevOffset 设置为 MAX(0 ,contentSize.height-frame.size.height)。

    这些东西不是必须的,但是你得到的滚动/表格视图会跳来跳去,试试看。

    【讨论】:

      【解决方案2】:

      UITableViewController 的头部字段中已经有委托协议。由于您的类不再是 UITableViewController,因此您需要手动将 UITableView 的委托协议头添加到您的 .h 文件中。

      当我创建一个具有 UITableView 的自定义视图控制器时,我也从 UITableViewController 开始,只是为了获取委托方法,但随后我将 UITableViewController 更改为 UIViewController,就像你所做的那样,并手动将委托协议添加到标题。

      如果需要,您可以查看 UITableViewController.h 并复制委托协议。

      供您参考:

      <UITableViewDelegate, UITableViewDataSource>
      

      所以你的 .h 文件应该看起来像这样:

      @interface MyTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
      

      另外,不要忘记将控制器的委托设置为接口构建器中的文件所有者,或代码中的self

      【讨论】:

        【解决方案3】:

        您可能还会发现使用框架(例如免费提供的 Sensible TableView 框架)要容易得多。这些框架通常提供开箱即用的所有数据输入单元格,并将代表您处理所有滚动/调整大小的琐事。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-27
          • 1970-01-01
          相关资源
          最近更新 更多