简体   繁体   中英

Uitableview cell custom unique ID

I have a table view and when a user selects a cell I want to log a unique id. I thought I could use the index but the numbers are not sequential (Ie 1,4,5,9,etc). Is there a way of defining a custom index or ID for a cell?

So I have the following cells in a table:

dog cat fish

the above cells have ids as below

2 dog 4 cat 8 fish

is there a way that when a user touches the fish cell it will return 8?

Indexpath.row would return 2 and I need 8. So is there a custom propertie I can set for each cell?

Not sure I totally understand the problem, but this should be 'sequential':

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%i", indexPath.row);
}

Update: Ok, so I think I get the confusion.

You need to have your dog, cat, fish, etc. in an NSArray that looks like [dog, cat, fish] that matches up with what you're displaying on the screen, or else you'll never be able to associate the two.

indexPath.row will be your pointer into that NSArray. So when you hit the second row, that code above will spit out 1. 1 in your array should your cat object, even though that's not the cat's id.

So then you do

myAnimal = [myArray objectAtIndex:indexPath.row];

to get your object, which in this case would be your cat. myAnimal.id will give you your 2.

Or, if your animals are dictionaries, it would be

[myAnimal objectForKey: @"id"]

would give you your 2.

Hopefully that helps a little more.

If your ids are actually all powers of two like you listed, you could just do a 2^(indexPath.row + 1)

Otherwise, you could also keep an NSDictionary that has your cell's labels as keys and your desired index number as their values. Or rework your tableview to use an NSDictionary instead of an NSArray or whatever it may be that you're using.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM