Joe Barbour
Joe Barbour

Reputation: 842

Editing UITableViewCell by tag

I have been trying to find a simple answer to something I think something that shouldn't be that difficult but I just either can't find a decent answer or can't wrap my head around it.

I am trying to change/edit the text label content of one specific tableview cell. So for examples sake I would like a UIButton outside of the UITableView but in the same View Controller to change the text within row 2, while keeping the others the same.

I am aware you use viewWithTag but other than that I cannot figure this out! Please help....

This is my code so far

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

    EntryCell *cell = (EntryCell *)[contentTable dequeueReusableCellWithIdentifier:@"Cell"];

    cell.mainLabel.tag = indexPath.row;
    cell.mainLabel.text = @"hello";

    return cell;

}

-(void)buttonPressed:(UIButton *)button {
    cell.mainLabel = (UILabel *)[contentTable viewWithTag:2];
    cell.mainLabel.text = @"goodbye";

}

Upvotes: 0

Views: 56

Answers (1)

Simon McLoughlin
Simon McLoughlin

Reputation: 8465

don't use viewWithTag, use the below to get a reference to the cell

-(void)buttonPressed:(UIButton *)button 
{
    EntryCell *cell = (EntryCell *)[tblView cellForRowAtIndexPath: [NSIndexPath indexPathForRow:2 inSection:0]];
    if(cell != nil)
    {
        cell.mainLabel.text = @"goodbye";
    }
}

EDIT

As david pointed out this will be overwritten if the cell is not visible as cellForRowAtIndexPath: will be called again when it becomes visible. Overwriting this change with whatever you have specified.

You will need to update your data model after this so the change is permanent

Upvotes: 1

Related Questions