简体   繁体   中英

image is reverting to original when scrolling uitableview

I have a button inside each cell. When it's pressed, the image is changed (basically a checkbox) to denote a selection. When you scroll to the bottom ... then scroll back up to the top. The image is reverted to the original image.

This question is pretty similar to this:

Preserve Cell Image After Scrolling UITableView

And others. But, I can't seem to find a good answer. I understand that's it's reverting back to how the uitableview is setup when the cell goes off the screen. But, how do I save the changed image to the uitableview so when it scrolls it doesn't revert to the original?

Thanks in advance! =)

It's changing back because cells are reused. When your cell is going off the screen it is taken out of the view and put back into the reuse pool. Then you're getting it out of the queue again in cellForRowAtIndexPath and setting it back up as the default.

The question you linked to is exactly what you should follow. You should store the state of your cell in your view controller and then when you set it up again in cellForRowAtIndexPath you should load that state and set up the cell appropriately.

One simple way for your method would be to have an NSArray which you set up to be the same size as the number of rows in your table and then in that just store an NSNumber for each row which contains a boolean value on or off for your selection state. When the user toggles, toggle the value in the array and then in cellForRowAtIndexPath read that value and set it up appropriately.

I'm assuming the checkbox in your table view cell is changing state to a selected state because a user selected it. You shouldn't use UI elements to maintain the state of your app. That is, when the user taps the checkbox, you should use that event to somehow reflect that state change in a data object in your app. Then, when that cell needs to be displayed again, you configure it with the state you previously saved. This allows for things like cell reuse, and view unloading and is all-around a good habit.

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