4m1r 4m1r - 1 month ago 16
iOS Question

iOS, Overriding cellForRowAtIndexPath to return custom cell

In order to add a property to a cell which I can use for identifying a row, I've created a custom cell which is subclassed from UITableViewCell. That part seems to work fine, but when I try to implement didSelectRowAtIndexPath, I'm unable to get my custom cell pointer, and thus cannot access that property. Do I need to override cellForRowAtIndexPath?

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

static NSString *MyIdentifier = @"MyReuseIdentifier";

NLSTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

if (cell == nil) {
cell = [[NLSTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
}

NSLog(@"indexPath: %ld", indexPath.row);
NSDictionary *cellDict = [self.sql getTitleAndIdForRow:indexPath.row];

NSArray *keys = [cellDict allKeys];
id rowId = [keys objectAtIndex:0];
id title = [cellDict objectForKey:rowId];

cell.textLabel.text = title;
cell.rowId = (NSUInteger)rowId;
return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];

//This message returns a UITableViewCell, not a my custom NLSTableViewCell
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

NSString *string = [[NSString alloc] init];
string = cell.textLabel.text;
NSUInteger rowId = cell.rowId;
NSLog(@"id: %ld, title: %@", rowId, string);
}

Answer

How about casting?

NLSTableViewCell *cell = (NLSTableViewCell *) [tableView cellForRowAtIndexPath:indexPath];
Comments