滚动到包含特定UITextField的UITableViewCell

问题描述:

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

我知道这应该滚动本身,但如果你的UIViewControllerUITableViewController派生(苹果称它应该是),那么UITableViewController类通过实现处理这种行为对你UITextFieldDelegateUIScrollViewDelegate等我的应用程序停止这样做,因为我改变派生自UIViewController并在视图控制器的顶部添加表视图UIView。所以基本上我错过了UITableViewController的功能,因为我(由于其他原因)选择从UIViewControler派生。

我一直这样做。我这样做的方式是我有一个被称为在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),因为在做这些事之前我有一些跳动的scrollViews。另外,如果原始偏移量(self.prevOffset)加上帧的高度大于内容大小(这也会导致跳跃,因为它将偏移设置得太低然后跳回),我将prevOffset设置为MAX( 0,contentSize.height-frame.size.height)。

这些东西并不是必需的,但你得到的是滚动/滚动的Scroll/TableViews,试用它们。

+0

完美谢谢@Jsdodgers – MrBeanzy 2013-03-19 23:43:41

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

当我创建一个具有UITableView的自定义视图控制器时,我首先使用UITableViewController来获取委托方法,但随后将UITableViewController更改为UIViewController,并手动将Delegate协议添加到标题。

如果你想,你可以看看UITableViewController.h并复制委托协议。

供您参考它们分别是:

<UITableViewDelegate, UITableViewDataSource> 

所以,你的.h文件中应类似于此:

@interface MyTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> 

另外,不要忘了控制器的代表设置为文件的所有者在“接口”构建器中,或者以代码的形式登录到self

您也可能会发现使用框架(如免费的Sensible TableView框架)更容易。这些框架通常提供所有数据输入单元,并代表您处理所有滚动/调整大小的杂事。