How do you load custom UITableViewCells from Xib files?

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

    Took Shawn Craver's answer and cleaned it up a bit.

    BBCell.h:

    #import 
    
    @interface BBCell : UITableViewCell {
    }
    
    + (BBCell *)cellFromNibNamed:(NSString *)nibName;
    
    @end
    

    BBCell.m:

    #import "BBCell.h"
    
    @implementation BBCell
    
    + (BBCell *)cellFromNibNamed:(NSString *)nibName {
        NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:NULL];
        NSEnumerator *nibEnumerator = [nibContents objectEnumerator];
        BBCell *customCell = nil;
        NSObject* nibItem = nil;
        while ((nibItem = [nibEnumerator nextObject]) != nil) {
            if ([nibItem isKindOfClass:[BBCell class]]) {
                customCell = (BBCell *)nibItem;
                break; // we have a winner
            }
        }
        return customCell;
    }
    
    @end
    

    I make all my UITableViewCell's subclasses of BBCell, and then replace the standard

    cell = [[[BBDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BBDetailCell"] autorelease];
    

    with:

    cell = (BBDetailCell *)[BBDetailCell cellFromNibNamed:@"BBDetailCell"];
    

提交回复
热议问题