Custom UITableViewCell Not Using .xib (Most Likely Because of Flaw in init Method)

后端 未结 3 1551
温柔的废话
温柔的废话 2020-12-10 09:36

I subclassed the UITableViewCell in order to customize it, but I think I\'m missing something because: 1) It\'s not working and 2) There are a couple of things I\'m confused

相关标签:
3条回答
  • 2020-12-10 09:47

    You have to load the cell from the .xib instead:

    if ( cell == nil ) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"CellXIBName" owner:nil options:nil][0];
    }
    
    // set the cell's properties
    
    0 讨论(0)
  • 2020-12-10 10:05

    The easiest way (available since iOS 5.0) to create a custom table view cell in a nib file is to use registerNib:forCellReuseIdentifier: in the table view controller. The big advantage is that dequeueReusableCellWithIdentifier: then automatically instantiates a cell from the nib file if necessary. You don't need the if (cell == nil) ... part anymore.

    In viewDidLoad of the table view controller you add

    [self.tableView registerNib:[UINib nibWithNibName:@"CueTableCell" bundle:nil] forCellReuseIdentifier:@"CueTableCell"];
    

    and in cellForRowAtIndexPath you just do

    CueTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CueTableCell"];
    // setup cell
    return cell;
    

    Cells loaded from a nib file are instantiated using initWithCoder, you can override that in your subclass if necessary. For modifications to the UI elements, you should override awakeFromNib (don't forget to call "super").

    0 讨论(0)
  • 2020-12-10 10:07
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *simpleTableIdentifier = @"CueTableCell";
    
        CueTableCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"CueTableCell XibName" owner:self options:nil];
            // Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
            cell = [array objectAtIndex:0];
        }
    
        return cell;
    }
    
    0 讨论(0)
提交回复
热议问题