开发者

Using indexPath in Table to reference array

I have a large array of data which I am displaying in a UITable. The table is broken into sections alphabetically. When a user selects a cell, I need to figure out where in the array that item is. The only identifying data 开发者_运维技巧in the cell is the label, which doesn't seem to be any help. The data in the array is not necessarily ordered alphabetically either. How can I figure out which item in the array they selected. Can I tie metadata or something to the table cell? I thought to make some kind of calculation based on the indexPath and the total count in the array, but since the array is not alphabetical, and the table is, this won't work.

Hope this makes sense. Thanks for any help.


It's typically a problem that solves itself. When you build the datasource for the tableview you have to sort your array in a way that makes sense for you to be able to display the information consistently, this is also going to lead to you being able to access it consistently.

In other words you're accessing something to build the table for your datasource calls of -tableView:cellforrowatindexpath:, the algorithm you use to build the cell will be the same you'll use to access the selected cell using the index path with didSelectCellAtIndexPath:.


You should look at UITableView Delegate method below:

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

It will give the index path of cell that was selected. Once you have the index path you can access the row and section property like so:

indexPath.row;
indexPath.section;

Once you have these two values you can then access your array object and see what item was selected in each section:

NSLog(@"Section %i, Row %i, Item %@", indexPath.section, indexPath.row, [array objectAtIndex:indexPath.row]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜