为UITableViewCell加载自定义XIB

Ara*_*yan 2 objective-c uitableview ios

我正在尝试使用自定义XIB文件UITableViewCell,但无论我做什么,表格单元格总是空的 - 我的XIB根本就没有加载.

没有任何错误.

这是我做的:

  1. 创建一个空应用程序,添加一个故事板,表视图控制器,添加一个新的UITableViewController,用表连接并设置一些示例项.

  2. 创建一个控制器作为UITableViewCell+ check选项的子类来生成XIB.

  3. 创建三个样本标签并将其添加为IBOutlets.

  4. 加载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;
}
Run Code Online (Sandbox Code Playgroud)

错误在哪里?有人能指出我正确的方向吗?

谢谢!

spa*_*sas 13

确保您已ItemCell在XIB中设置标识符,并且还设置了表数据源.然后转移registerNibviewDidLoad

-(void)viewDidLoad {
        //...
       self.tableview.dataSource = self;
       [self.tableView registerNib:[UINib nibWithNibName:@"CustomTableViewCell" bundle:nil] forCellReuseIdentifier:@"ItemCell"];

        }
Run Code Online (Sandbox Code Playgroud)

和in cellForRowAtIndexPath:

CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ItemCell" forIndexPath:indexPath];
Run Code Online (Sandbox Code Playgroud)

并删除if (!cell)块,无论如何它将不会被使用.