[英]How do I reload a UITableView's data when I don't know how many sections there will be?
我對如何更改數據后如何在UITableView
重新加載單元格有些困惑。 特別是,我一直感到困惑的是,新數據的部分可能比當前顯示的部分更多或更少。 我知道這里有reloadSections:withRowAnimation:
方法,但是這需要1:1替換,而我可能有也可能沒有。
我只想告訴UITableView
所有內容並像第一次一樣重新加載。 我希望有人對此有所啟發。
提前致謝!
更新
這是我正在使用的代碼,我發現問題是調用reloadData
后單元不出隊...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
NSLog(@"%@", cell);
if (cell == nil) {
NSLog(@"%d; %d", indexPath.section, vehicle.inventoryCategoriesCount);
if (indexPath.section < vehicle.inventoryCategoriesCount) {
NSLog(@"Grouped cell");
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Cell"] autorelease];
NSString *model = [[[vehicle.inventory filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"category == %@", [vehicle.inventoryCategories objectAtIndex:indexPath.section]]] valueForKeyPath:@"@distinctUnionOfObjects.model"] objectAtIndex:indexPath.row];
cell.textLabel.text = model;
cell.detailTextLabel.text = [NSString stringWithFormat:@"%d", [[vehicle.inventory filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"model == %@", model]] count]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
} else {
NSLog(@"Remove cell");
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"] autorelease];
cell.textLabel.text = @"Remove an Item";
cell.textLabel.textColor = [UIColor redColor];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
}
NSLog(@"Adding a cell");
return cell;
}
您可以在表視圖上調用reloadData
。
[myTableView reloadData];
該文檔位於: http : //developer.apple.com/library/ios/#documentation/uikit/reference/UITableView_Class/Reference/Reference.html
如果您使用核心數據和獲取的結果控制器,則非常簡單。 實際上,我相信如果您構建一個帶有表視圖的示例核心數據項目,就可以看到這一點。
我想到兩種不同的方法:控制器didChangeSection可能正是您想要的。 第一個是fetchedresultscontroller委托協議的一部分。 第二個是tableviewdatasource協議的一部分。
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
switch(type) {
case NSFetchedResultsChangeInsert:
[self.noteTableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.noteTableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
另一個是:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[fetchedResultsController sections] count];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.