Reputation: 6594
I'd like to create a custom UITableViewCell subclass that loads content asynchronously using a URL connection. I've got a UITableViewCell subclass that handles all of this and a Nib file that defines the layout of the cell, but I'm having trouble linking the two. Here's the code I'm using 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 a request URL to the UITableViewCell subclass, which handles loading in the setRequestURL
method.
In the FavouriteCell class I've kept the initWithStyle:reuseIdentifier:
method as is, and in the Nib I've set FavCellIdentifier as the identifier, and FavouriteCell as the class. Now how do I make the FavouriteCell class load the Nib?
Upvotes: 3
Views: 3033
Reputation: 11598
In order to use the nib/xib file, you're going to have to instantiate the FavouriteCell
differently.
Try this:
UITableViewCell
to be a subclass of FavouriteCell
instead of the default UITableViewCell
in your xib. Do this by:
FavouriteCell
.File's Owner
property to be the UIViewController
where you want to display your custom UITableViewCell
(pretty much same process as step #1).IBOutlet
property of type FavouriteCell
to your UIViewController
. Name it whatever you like (I'm going to call it cell
).UITableViewCell
, connect the IBOutlet for the cell
property in File's Owner to your custom 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;
}
Upvotes: 7