Pages

August 30, 2013

Get a UITableViewCell from NIB (aka XIB) file

UITableViewCell + Interface Builder = Great work!
Ok, but sometimes I need to load a NIB file programmatically... And so I use a useful function...


/** Returns a UITableViewCell loaded from NIB file (.xib).

 @param nibToLoad The file name to load.
 @param owner The object to assign as the nib’s File's Owner object.
 @param identifier The cell identifer to look for in order to reuse cells.
 @return Returns the UITableViewCell object properly initialized with the owner properties.

 */
+ (UITableViewCell *)tableViewCellFromNib:(NSString *)nibToLoad ofOwner:(id)owner withIdentifier:(NSString *)identifier {

    if (!nibToLoad || [nibToLoad isEqualToString:@""]) { return nil; }
    if (!identifier || [identifier isEqualToString:@""]) { return nil; }

    NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:nibToLoad owner:owner options:nil];
    NSEnumerator *nibEnumerator = [nibContents objectEnumerator];

    UITableViewCell *tempCell = nil;
    NSObject *tempNibItem = nil;

    while ( (tempNibItem = [nibEnumerator nextObject]) != nil ) {
        if ( [tempNibItem isKindOfClass:[UITableViewCell class]] ) {
            tempCell = (UITableViewCell*) tempNibItem;
            if ( [tempCell.reuseIdentifier isEqualToString:identifier] ) {
                break;
            }
        }
    }
    return tempCell;
}



Download the ready-for-use source file (.m) of Get a UITableViewCell from NIB (aka XIB) file

No comments:

Post a Comment