iOS:自定义TableViewCell - 初始化自定义单元格

Tvd*_*Tvd 5 objective-c uitableview ios

在我的TableView中,我有一个NSMutableArray*currList的dataSource - 它包含对象Agent的对象.我创建了自定义的TableCell并正确设置了所有内容.我在显示数据时发现问题:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     static NSString *simpleTableIdentifier = @"ChatListCell";

     // Custom TableViewCell
     ChartListCell *cell = (ChartListCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

     if (cell == nil) {
           // I believe here I am going wrong
           cell = [[ChartListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
           NSLog(@"Cell = %@", cell);  // Shows null
     }
     /*
     With UITableViewCell, things are working perfectly fine
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
     if (cell == nil) {
         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
     }
     */
     Agent *agent = (Agent *)[currChatList objectAtIndex:indexPath.row];
     NSLog(@"Agent name - %@", agent.name);   // Prints proper data
     cell.nameLabel.text = agent.name;
     cell.thumbImageView.image = [UIImage imageNamed:agent.photo];
     cell.timeLabel.text = agent.chatTime;

     return cell;
}
Run Code Online (Sandbox Code Playgroud)

正如您在上面的代码注释中看到的,如果我注释自定义ChartListCell并使用UITableViewCell,它可以正常工作.但是使用ChartListCell,没有任何内容出现,在日志中我得到"Cell = null"并且代理名称正确显示.单元格不应为空.为什么它是空的,任何人都可以帮我解决这个问题.我在哪里做错了?

任何帮助都非常感谢.

谢谢

Moh*_*hit 15

导入自定义单元格文件并尝试此操作

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *simpleTableIdentifier = @"ChartListCell";

ChartListCell *cell = (ChartListCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ChartListCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];

}         

 Agent *agent = (Agent *)[currChatList objectAtIndex:indexPath.row];
 NSLog(@"Agent name - %@", agent.name);   // Prints proper data
 cell.nameLabel.text = agent.name;
 cell.thumbImageView.image = [UIImage imageNamed:agent.photo];
 cell.timeLabel.text = agent.chatTime;

return cell;
}
Run Code Online (Sandbox Code Playgroud)

  • 使用第0个元素因为数组nib中只有一个元素.因为只有一个名为ChartListCell的nib文件 (2认同)