user1288005
user1288005

Reputation: 920

change iPhone tableview cell label text on didSelectRowAtIndexPath

I want to change text of custom UITableviewCell text on didSelectRowAtIndexPath and I am using following code:-

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.lblName.text=@"cambridge";
[tableView deselectRowAtIndexPath:indexPath animated:NO];

 }

but I am getting "request for member 'levelNo' in something not a structure or union". However I am able to set it at cellForRowAtIndexPath. Please help

Upvotes: 1

Views: 5051

Answers (3)

janusfidel
janusfidel

Reputation: 8106

try

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 YourCustomCell *cell = (YourCustomCell*)[tableView cellForRowAtIndexPath:indexPath];
 cell.lblName.text=@"cambridge";
 [tableView deselectRowAtIndexPath:indexPath animated:NO];

 //update your data, your data source must be mutable
 //in case your array content are NSString, just do
  [yourMutableArrayDataSource replaceObjectAtIndex:indexPath.row withObject:@"cambridge"];

 //or if your data array holds NSDictionary. you can just initialize new dictionary 
 //as a replacement of the object in case you dont want your dictionary to be mutable
 NSDictionary *tempDict = [NSDictionary dictionaryWithObjectsAndKeys:@"cambridge",@"text",@"yourOtherData",@"otherData" nil];
  [yourMutableArrayDataSource replaceObjectAtIndex:indexPath.row withObject:tempDict];

 }

as mentioned by Maulik (thank you), the lblName text will change back to its original text when the cell scrolls. you might want to update your data source to keep the new data. **answer edited

Upvotes: 3

Maulik
Maulik

Reputation: 19418

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
 YourCustomCell *cell = (YourCustomCell*)[tableView cellForRowAtIndexPath:indexPath];
 cell.lblName.text=@"cambridge";
 [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

By above code of janusfidel , label's text will be changed. But when you scroll the table , I guess value will be changed to original value.

You also need to update your data source(that is your array ) when you want to change original data.

Upvotes: 0

Abhishek
Abhishek

Reputation: 2253

(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath    
{
  UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
 cell.lblName.text=@"New text Here";
 [tableView deselectRowAtIndexPath:indexPath animated:NO];
 [tableView reloadData];
}

Upvotes: 0

Related Questions