Michael
Michael

Reputation: 277

How to understand which UITableViewCell has been selected

I have a list of NSStrings stored in an NSMutableArray, each value in the NSMutableArray has been assigned to a UITableViewCell. Using the following method:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

How do I figure out which cell was selected. I'm looking for some kind of value through NSIndexPath or any other method to change the icon of a UITableViewCell when it is selected. After I know which cell has been selected, I'd reassign the cell to the new image, and then reload the data using: [self.homeworkTable reloadData].

I'm looking for some kind of simple return value, like 0 if the first cell is selected, etc. I've tried utilizing the NSIndexPath with no luck, as an NSIndexPath is not an NSString. How would I go about doing this?

EDIT

I understand the answer may already be on Stack Overflow, I simply haven't found it, and redirecting me to the answer would be very much appreciated.

Upvotes: 1

Views: 50

Answers (3)

meda
meda

Reputation: 45490

You can get it directly didSelectRowAtIndexPath (that's the whole point!) using indexPath.row

- (void)tableView:(UITableView *)tableView 
                        didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
      int index = indexPath.row;
  //....

It will match the index of your datasource array.

Sometimes you will need to get it from outside didSelectRowAtIndexPath deleguate method, you can do it the following way:

NSIndexPath *indexPath = [self.homeworkTable indexPathForSelectedRow];
int index = indexPath.row;

Upvotes: 1

StevenOjo
StevenOjo

Reputation: 2488

You should use indexPath.row, this gets you the row that you selected in this tableview.

You should also check out the documentation on NSIndexPath:

https://developer.apple.com/library/Mac/documentation/Cocoa/Reference/Foundation/Classes/NSIndexPath_Class/Reference/Reference.html

Upvotes: 0

ColdLogic
ColdLogic

Reputation: 7265

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

Upvotes: 1

Related Questions