How do you load custom UITableViewCells from Xib files?

前端 未结 23 1761
抹茶落季
抹茶落季 2020-11-22 11:11

The question is simple: How do you load custom UITableViewCell from Xib files? Doing so allows you to use Interface Builder to design your cells. The answer app

23条回答
  •  太阳男子
    2020-11-22 11:39

    The correct way to do it is to create a UITableViewCell subclass implementation, header, and XIB. In the XIB remove any views and just add a table cell. Set the class as the name of the UITableViewCell subclass. For file owner, make it the UITableViewController subclass class name. Connect the file owner to the cell using the tableViewCell outlet.

    In the header file:

    UITableViewCell *_tableViewCell;
    @property (assign) IBOutlet UITableViewCell *tableViewCell;
    

    In the implementation file:

    @synthesize tableViewCell = _tableViewCell;
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *kCellIdentifier = @"reusableCell";
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
        if (cell == nil) {
            [[NSBundle mainBundle] loadNibNamed:kCellIdentifier owner:self options:nil];
            cell = _tableViewCell;
            self.tableViewCell = nil;
        }
    
        return cell;
    }
    

提交回复
热议问题