4m1r
4m1r

Reputation: 12542

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);
}

Upvotes: 0

Views: 1941

Answers (2)

Randoramma
Randoramma

Reputation: 133

In your viewDidLoad 2 things to check.
1. That you register the class for the table view cell. 2. That you use the custom class in your registration statement. ie.

[myTableView registerClass:[YOUR_CUSTOM_CELL_CLASS class] forCellReuseIdentifier:YOUR_CUSTOM_CELL_CLASS_REUSE_ID];

Casting the subclassed Table view cell in the dequeue statement did not work for me.

Cheers!

Upvotes: 1

idmean
idmean

Reputation: 14875

How about casting?

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

Upvotes: 4

Related Questions