我试图使用delegate从详细信息ViewController中更新MasterViewController中的TableView。我从委托方法中调用了Reloaddata,但这并没有涉及。我仍然无法解决。
这是我在MasterViewController中的代表方法
- (void)updateScore:(DetailViewController *)controller withScore:(NSUInteger)score {
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:_selectedIndexPath];
NSLog(@"%@", cell.detailTextLabel.text);
cell.detailTextLabel.text = [NSString stringWithFormat:@"Best score: %lu", (unsigned long)score];
[self.tableView reloadData];
NSLog(@"%@", cell.detailTextLabel.text);
}
来自nslog the cell.detailtextlabel.text已更新,但TableView未重新加载
谢谢
您需要确保您的视图控制器是tableview委托和dataSource
如果您使用的是故事板,则在Connections Inspector下,您的桌面需要将视图控制器设置为DataSource和DeTaSource
如果您只想在ViewDidload方法中的ViewController.m文件中执行此操作,则可以使用这些行
self.tableView.delegate = self;
self.tableView.dataSource = self;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//other init
}
if(_selectedIndexPath.row == indexPath.row && _selectedIndexPath.section == indexPath.section){
cell.detailTextLabel.text = [NSString stringWithFormat:@"Best score: %lu", (unsigned long)score];
}
}
您可以尝试在上面的cellForRowAtIndexPath
中移动代码,然后tableview reloaddata
-
[self.tableView reloadData]
更新表中的所有可见单元格。它调用numberOfSectionsInTableView
,numberOfRowsInSection
,cellForRowAtIndexPath
等。换句话说:它完全更新了桌子。 -
设置单元素内容的唯一正确方法是将其设置在
cellForRowAtIndexPath
中。代码:if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; //other init}
从iOS 6开始,如果您使用故事板,就永远不会被打电话。
因此,您的代码:
- 使用不正确的方法来设置单元格内容。
- 用
[self.tableView reloadData]
清除所有设置。
解决方案:
- 在
__strong ivar
或property
中保存score
。 - 致电
[self.tableView reloadData]
。它在适当的时间调用cellForRowAtIndexPath
。 - 在
cellForRowAtIndexPath
方法中设置新的score
。
建议:使用:
dispatch_async(dispatch_get_main_queue(), ^(){ [self.tableView reloadData]; });
从代表快速返回,而不要等到表格更新。