2013-03-19 45 views
1

我有一個UITableView與靜態自定義UITableViewCell s,我需要滾動文本字段到視圖中,因爲當前它們隱藏在鍵盤後面,按下返回鍵並且下一個響應者是組。我知道我需要使用scrollToRowAtIndexPath:atScrollPosition:animated:。我將如何去滾動到其中一個文本框?滾動到包含特定UITextField的UITableViewCell

我知道這應該滾動本身,但如果你的UIViewControllerUITableViewController派生(蘋果稱它應該是),那麼UITableViewController類通過實現處理這種行爲對你UITextFieldDelegateUIScrollViewDelegate等我的應用程序停止這樣做,因爲我改變派生自UIViewController並在視圖控制器的頂部添加表視圖UIView。所以基本上我錯過了UITableViewController的功能,因爲我(由於其他原因)選擇從UIViewControler派生。

回答

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),因爲在做這些事之前我有一些跳動的scrollViews。另外,如果原始偏移量(self.prevOffset)加上幀的高度大於內容大小(這也會導致跳躍,因爲它將偏移設置得太低然後跳回),我將prevOffset設置爲MAX( 0,contentSize.height-frame.size.height)。

這些東西並不是必需的,但你得到的是滾動/滾動的Scroll/TableViews,試用它們。

+0

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

0

UITableViewController具有已經在標題字段中的委託協議。由於您的類不再是UITableViewController,因此您需要手動將UITableView的委託協議標頭添加到.h文件中。

當我創建一個具有UITableView的自定義視圖控制器時,我首先使用UITableViewController來獲取委託方法,但隨後將UITableViewController更改爲UIViewController,並手動將Delegate協議添加到標題。

如果你想,你可以看看UITableViewController.h並複製委託協議。

供您參考它們分別是:

<UITableViewDelegate, UITableViewDataSource> 

所以,你的.h文件中應類似於此:

@interface MyTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> 

另外,不要忘了控制器的代表設置爲文件的所有者在「接口」構建器中,或者以代碼的形式登錄到self

0

您也可能會發現使用框架(如免費的Sensible TableView框架)更容易。這些框架通常提供所有數據輸入單元,並代表您處理所有滾動/調整大小的雜事。

相關問題