简体   繁体   中英

Get the values in checked cells in a UITableView

I have a UITableView with each cell is having a UITableViewCellAccessoryCheckmark . The user can check and uncheck the cells depending on his preference. The user can check/select multiple cells in the tableview. A selected/checked cell can be unchecked and rechecked again on user preference. I have a done button in the UITableViewController . On its click, I need to return to the previous view, before that I have to have a collection of the text in the checked cells(only checked cells). How can I do this.

I was planning on developing a logic, by keeping an NSMutableArray and update it on - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath , when a cell gets checked/selected. But when every time a cell is unchecked I have to remove the item from the array and if the cell is checked again, then I have to add it again. I reckon thats not the right way to do this. What would be the right way to do this. I couldn't find a question of similar kind here in Stackoverflow, which is very unusual. Would be helpful if someone could post a link, if the question was asked before.

Maintain two arrays, like this:

@property (nonatomic, retain) NSMutableArray *features, *selectedFeature;

synthesize them in .m file. initialize your both arrays something like this in viewDidLoad :

self.features = [NSArray arrayWithMyOwnResourceLikeDownloadedFromServerOrWhatever];
self.selectedFeature = [NSMutableArray array];

Then do something like this in didSelectRowAtIndex :

NSString * stirng = [features objectAtIndex:indexPath.row];
if ([self.selectedFeature containsObject:stirng]) {
    [self.selectedFeature removeObject:stirng];
}
else{
   [self.selectedFeature addObject:stirng];
}

and in your cellForRowAtIndexPath :

NSString * stirng = [features objectAtIndex:indexPath.row];
[cell.textLabel setText:stirng];
if ([self.selectedFeature containsObject:stirng]) {
   //it is selected feature
   [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}
else{
   //it is un-selected feature
   [cell setAccessoryType:UITableViewCellAccessoryNone];
}

Create a boolean array of the same length as the number of checkable cells and update the value on click events. If the table content is dynamic, you can use methods provided by NSMutabeArray to keep the boolean array in accordance with the table content. Upon return use the array to grab the text you need.

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