简体   繁体   中英

One click, multiple actions Custom Cell of TableView

What I do

I have a created a custom cell which has a button with a specific image on it. Now depending on some conditions I set that image image1.jpg or image2.jpg .

How I do that

The custom cell is created by creating a protocol where I click that buttons action, I notice in the main interface, that the button is pressed and I pass as a parameter the button instance.

Issue

Now, the problem is when I click that button in a specific cell, I change cell.button 's image, but also with that, when I scroll down, I see that there are other cells that have changed their image .

Any idea why is this happening?

Due to the reuse of cells by the UITableView, when the cell moves out of the screen, it is moved to a queue and then reused when there are new cells to load.

If you want to keep each cell's property unique, you will have to reconstruct its values every time. For that you can keep some kind of data array that stores the state/condition of each cell. The array will be ordered by the indexPath of the tableView, and then you can just fetch the state from the array based on the indexPath and update the cell to be the right image.

What is happening is that when you change the image of your cell and later scroll down or up, your cell is being reused to present another information.
To fix that you should check your UITableView data source, see if you're reusing cells in this method:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath


I'd recommend to configure the cell before returning it in the previous method, and assign the appropiate image for the button at that time.
To achieve that you'd need some mechanism for remembering the state of each cell.

For more information about cell reusing and cell in general you could go to the Apple Docs for UITableViewCell

As described in above answer you can manage button selected and unselected state in array for that you can even add one key in the array that you are using for the data to display.

and on didselect event of table you can change the key of selected field like this

 NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
            NSDictionary *oldDict = self.dict_trans_Details ;
            [newDict addEntriesFromDictionary:oldDict];
            [newDict setObject:status forKey:@"transactionstatusid"];
            [table_transdetails_array replaceObjectAtIndex:self.indexValue withObject:newDict];

Thanks.

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