[英]Implementing Prev./Next buttons in UITableView to make first responder a UITextField in a non-visible cell
在我的應用程序中,我在每個單元格中都有一個帶UITextField
的UITabeView
。 但是我在實現上一個/下一個按鈕時遇到麻煩,使上一個/下一個UITableViewCell
內的文本字段成為第一個響應者。
我已經將UITableViewCell
類子類化為在按下prev./next按鈕時調用它的delegate
的某個方法,並將單元格本身作為此方法的參數傳遞(因此我可以獲取其索引路徑來計算哪個是必須首先響應文本字段的單元格的索引路徑
在委托方法I的實現中:
-cellForRowAtIndexPath:
方法將textfield作為第一響應者的單元格 問題是-cellForRowAtIndexPath:
方法只有在可見時才返回單元格。 因此,當單元格不可見時,它將返回nil
,並且上述算法將無法工作,而當單元格在屏幕上時,它將正常工作。
這是我的上傳代碼。 按鈕,前提是MUInfoMateriaTableViewCell
是我的UITableViewCell
子類,並且它有一個textField
屬性,返回其文本字段:
- (void)prevButtonPressedInCell:(MUInfoMateriaTableViewCell *)cell
{
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
NSIndexPath *previousIndexPath = [NSIndexPath indexPathForRow:indexPath.row-1 inSection:indexPath.section];
MUInfoMateriaTableViewCell *newCell = (MUInfoMateriaTableViewCell *)[self.tableView cellForRowAtIndexPath:previousIndexPath];
[newCell.textField becomeFirstResponder];
}
有沒有辦法“獲得”一個不可見的單元格,所以我可以讓它的文本字段成為第一個響應者? 或者你能建議我另一種解決這個問題的算法嗎?
您可以通過多步驟過程解決此問題:
NSIndexPath
並調用[self.tableView scrollToRowAtIndexPath:atScrollPosition:animated:]
將其帶入視圖 tableView:willDisplayCell:forRowAtIndexPath:
當所需的單元格變得可見時調用所需單元格上的becomeFirstResponder
,它與所需的單元格或索引路徑匹配 最后一步很重要,因為如果接收者不是任何窗口的子視圖,則調用becomeFirstResponder
不會做任何事情。
使用scrollToRowAtIndexPath:atScrollPosition:animated:
滾動表格視圖使單元格可見。
例如
- (void)prevButtonPressedInCell:(MUInfoMateriaTableViewCell *)cell
{
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
NSIndexPath *previousIndexPath = [NSIndexPath indexPathForRow:indexPath.row-1 inSection:indexPath.section];
[self.tableView scrollToRowAtIndexPath:previousIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
MUInfoMateriaTableViewCell *newCell = (MUInfoMateriaTableViewCell *)[self.tableView cellForRowAtIndexPath:previousIndexPath];
[newCell.textField becomeFirstResponder];
}
問題是-cellForRowAtIndexPath:方法只有在可見時才返回單元格。
那是因為當它的行不可見時,單元格不存在。 UITableView只保留繪制表所需的那些單元格。 這就是為什么你滾動表時會得到很多-tableView:cellForRowAtIndexPath:
消息 - 表要求它的數據源提供它沒有的單元格。
如果你想使用當前的方法,你需要滾動表格,以便可以看到要編輯的行,如Gabriele Petronella的回答所示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.