我正在尝试为 UITableViewCell
使用自定义 XIB 文件,但无论我做什么,表格单元格始终为空 - 我的 XIB 根本没有加载。
没有任何错误。
这是我的做法:
创建一个空应用程序,添加 Storyboard、表格 View Controller ,添加新的
UITableViewController
,将其与表格 Hook 并设置一些示例项目。创建一个 Controller 作为
UITableViewCell
的子类 + 选中生成 XIB 的选项。创建三个示例标签并将它们添加为
IBOutlets
。加载 XIB 文件并尝试将其设置为单元格。
代码:
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableView.delegate = self;
items = [[NSMutableArray alloc] init];
for (int i = 0; i < 20; i++) {
ItemObject *item = [ItemObject new];
item.topLabel = [NSString stringWithFormat:@"Top %d", i];
item.leftLabel = [NSString stringWithFormat:@"Left %d", i];
item.rightLabel = [NSString stringWithFormat:@"Right %d", i];
[items addObject:item];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return items.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"ItemCell";
// Set up the cell.
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (!cell) {
[tableView registerNib:[UINib nibWithNibName:@"CustomTableViewCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
}
ItemObject *currentObject = [items objectAtIndex:indexPath.row];
cell.topLabel.text = currentObject.topLabel;
cell.leftLabel.text = currentObject.leftLabel;
cell.rightLabel.text = currentObject.rightLabel;
// General cell and table settings.
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[tableView setSeparatorColor:[UIColor clearColor]];
return cell;
}
错误可能在哪里?有人可以指出我正确的方向吗?
谢谢!
最佳答案
确保您已经在 XIB 中设置了 ItemCell
标识符,并且您的表数据源也已设置。然后将你的 registerNib
移动到 viewDidLoad
-(void)viewDidLoad {
//...
self.tableview.dataSource = self;
[self.tableView registerNib:[UINib nibWithNibName:@"CustomTableViewCell" bundle:nil] forCellReuseIdentifier:@"ItemCell"];
}
和 cellForRowAtIndexPath:
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ItemCell" forIndexPath:indexPath];
并删除 if (!cell)
block ,它无论如何都不会被使用。
关于ios - 为 UITableViewCell 加载自定义 XIB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25010888/