[英]UISearchDisplayController and UITableView prototype cell crash
我在故事板中有一個UIViewController
設置,帶有tableview
和UISearchDisplayController
。
我正在嘗試使用self.tableview中的自定義原型單元格(它連接到故事板中的主表視圖)。 如果self.tableview
在我加載視圖時至少返回了1個單元格,但是如果self.tableview
沒有加載單元格(因為沒有數據),並且我加載了UISearchBar
並搜索了cellForRowAtIndexPath:
方法崩潰:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomSearchCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"CustomSearchCell" forIndexPath:indexPath];
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
-(void)configureCell:(CustomSearchCell *)cell atIndexPath:(NSIndexPath *)indexPath {
User *user = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.nameLabel.text = user.username;
}
錯誤:
*** Assertion failure in -[UITableViewRowData rectForRow:inSection:heightCanBeGuessed:]
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'request for rect at invalid index path (<NSIndexPath: 0x9ef3d00> {length = 2, path = 0 - 0})
我的fetchedResultsController似乎在調用上述方法時有數據(1個部分,2行)。 它在dequeueReusableCellWithIdentifier
行崩潰。
任何指針/想法? 它應該將原型單元格從self.tableview
取出,但我的猜測是在self.tableview
中沒有創建,所以這是原因?
除了擁有主表之外,UISearchDisplayController還管理它自己的UITableView(過濾表)。 篩選表中的單元格標識符與主表不匹配。 您還希望不是通過indexPath獲取單元格,因為兩個表在行數方面可能相互之間存在很大差異等。
所以不要這樣做:
UITableViewCell *cell =
[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
而是這樣做:
UITableViewCell *cell =
[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
我通過將原型單元復制到一個新的xib來解決這個問題:
在viewDidLoad中:
[self.searchDisplayController.searchResultsTableView registerNib:[UINib nibWithNibName:@"CustomSearchCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"CustomSearchCell"];
並更新了cellForRowAtIndexPath以使用方法的tableview而不是原始的self.tableview:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomSearchCell" forIndexPath:indexPath];
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
這是一個古老的話題,但如果有人遇到同樣的問題,對我而言,這與在viewDidLoad中擁有這一行有關
self.tableView.estimatedRowHeight = 80;
同時在不同條件下實現具有可變高度的heightForRowAtIndexPath委托方法
if (indexPath.row == 0) {
return 44 + cellTopSpacing;
} else {
return 44;
}
刪除估計的行高解決了它。
如果在方法celForRowAtIndexPath中使用àUISearchDisplayController,則必須使用tableView參數method而不是控制器的retain指針。
嘗試使用此代碼
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomSearchCell" forIndexPath:indexPath];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.