How do you load custom UITableViewCells from Xib files?

前端 未结 23 2163
抹茶落季
抹茶落季 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:37

    Reloading the NIB is expensive. Better to load it once, then instantiate the objects when you need a cell. Note that you can add UIImageViews etc to the nib, even multiple cells, using this method (Apple's "registerNIB" iOS5 allows only one top level object - Bug 10580062 "iOS5 tableView registerNib: overly restrictive"

    So my code is below - you read in the NIB once (in initialize like I did or in viewDidload - whatever. From then on, you instantiate the nib into objects then pick the one you need. This is much more efficient than loading the nib over and over.

    static UINib *cellNib;
    
    + (void)initialize
    {
        if(self == [ImageManager class]) {
            cellNib = [UINib nibWithNibName:@"ImageManagerCell" bundle:nil];
            assert(cellNib);
        }
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *cellID = @"TheCell";
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if(cell == nil) {
            NSArray *topLevelItems = [cellNib instantiateWithOwner:nil options:nil];
            NSUInteger idx = [topLevelItems indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop)
                                {
                                    UITableViewCell *cell = (UITableViewCell *)obj;
                                    return [cell isKindOfClass:[UITableViewCell class]] && [cell.reuseIdentifier isEqualToString:cellID];
                                } ];
            assert(idx != NSNotFound);
            cell = [topLevelItems objectAtIndex:idx];
        }
        cell.textLabel.text = [NSString stringWithFormat:@"Howdie %d", indexPath.row];
    
        return cell;
    }
    

提交回复
热议问题