【发布时间】:2013-09-03 09:17:14
【问题描述】:
希望有人可以建议我使用自定义标签填充UITableViewCell 的正确方法。我一直遇到同样的问题,要么标签是空白的,要么当表格填满 cells 重复使用的标签时显示重叠的 label 文本。
我遵循了这里为其他人提供的建议,但每次我这样做都会有问题。
** 更新**
我已将代码更改为以下代码,并且大部分代码都可以正常工作,除非我选择一个单元格时标签重叠,如下面的屏幕截图所示。我正在使用的教程的代码可以在这里找到:https://github.com/funkyboy/Core-Data-on-iOS-5-Tutorial--How-To-Work-with-Relations-and-Predicates
这是我的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
FailedBankInfo *info = [_fetchedResultsController objectAtIndexPath:indexPath];
CGRect infoFrame = CGRectMake(10, 10, 200, 16);
UILabel *infoLabel = [[UILabel alloc] initWithFrame:infoFrame];
infoLabel.textColor = [UIColor blackColor];
infoLabel.backgroundColor = [UIColor yellowColor];
infoLabel.font = [UIFont systemFontOfSize:12];
infoLabel.textAlignment = NSTextAlignmentCenter;
infoLabel.tag = indexPath.row;
infoLabel.text = [NSString stringWithFormat:@"%@, %@", info.city, info.state];
[cell addSubview:infoLabel];
return cell;
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
FailedBankInfo *info = [_fetchedResultsController objectAtIndexPath:indexPath];
UILabel *theLabel = (UILabel *)[cell.contentView viewWithTag:indexPath.row];
theLabel.text = [NSString stringWithFormat:@"%@, %@",
info.city, info.state];
}
因为我将原型Cell 与Core Data 一起使用,而fetchedresultcontroller 永远不会调用if(!cell)。我将标签更改为 indexPath.row 编号。如果您使用预定义的 cell 类型,我遵循的每个教程都可以正常工作。如果我将自定义与我自己的标签一起使用,它永远不会奏效。我不应该对 tableview 数据使用 fetchedresultscontroller 吗?如果我在详细视图中更改城市标题并将其保存,则会调用以下代码:
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray
arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray
arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
以下是一些截图:
【问题讨论】:
-
你试过我的解决方案了吗?如果是并且有效,请将其标记为已接受:)
-
@MongiZaidi 是的,我做了 Mongi,但标签根本不显示。
标签: ios iphone uitableview core-data