Subclassing UITableViewCell with its own Nib

I would like to create a custom subclass of UITableViewCell that loads content asynchronously using a URL connection. I have a subclass of UITableViewCell that handles all this and a Nib file that defines the layout of the cell, but I am having trouble linking the two. Here is the code I use in tableView:cellForRowAtIndexPath:

static NSString *FavCellIdentifier = @"FavCellIdentifier";

FavouriteCell *cell = [tableView dequeueReusableCellWithIdentifier:FavCellIdentifier];

if (cell == nil)
{
    cell = [[[FavouriteCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:FavCellIdentifier] autorelease];
}

cell.requestURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@?%@=%i", URL_GET_POST_STATUS,
                                           URL_PARAM_SERIAL,
                                           [[self.favourites objectAtIndex:indexPath.row] intValue]]];

return cell;

This gives the request URL to a subclass of UITableViewCell that handles the loading in the method setRequestURL.

In the FavoriteCell class, I saved the method initWithStyle:reuseIdentifier:as is, and in Nib, I set FavCellIdentifier as the identifier, and FavoriteCell as the class. Now, how to get the FavoriteCell class to load Nib?

+3
source
1

nib/xib, FavouriteCell -.

:

  • , UITableViewCell FavouriteCell UITableViewCell xib. :
    • Interface Builder.
    • " " , " " " " FavouriteCell.
  • File Owner UIViewController, UITableViewCell ( , 1).
  • IBOutlet FavouriteCell UIViewController. ( cell).
  • xib UITableViewCell, IBOutlet cell File Owner UITableViewCell.
  • :

- (FavouriteCell *)tableView:(UITableView *)tableView 
       cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellId = @"FavCellId";
    FavouriteCell *cell = [tableView dequeueReusableCellWithIdentifier:CellId];
    if (!cell) {
        // Loads the xib into [self cell]
        [[NSBundle mainBundle] loadNibNamed:@"FavouriteCellNibName" 
                                      owner:self 
                                    options:nil];
        // Assigns [self cell] to the local variable
        cell = [self cell];
        // Clears [self cell] for future use/reuse
        [self setCell:nil];
    }
    // At this point, you're sure to have a FavouriteCell object
    // Do your setup, such as...
    [cell setRequestURL:[NSURL URLWithString:
                  [NSString stringWithFormat:@"%@?%@=%i", 
                      URL_GET_POST_STATUS, 
                      URL_PARAM_SERIAL, 
                      [[self.favourites objectAtIndex:indexPath.row] intValue]]
     ];
    return cell;
}
+7

All Articles