简体   繁体   中英

Saving uibutton state in custom cell Swift

I have a custom cell with two uibuttons . Click on one of the buttons appends rows also based on a custom cell with two uibuttons .

Once the button is clicked i'm changing it's alpha to 50% and the boolean isPressed is set to true. So the next time user presses the button it would produce an alert view with error.

The issue is - each time i scroll - the cells with the buttons are being reused and those two rules are applied chaotically.

I've browsed answers on stack, but haven't seen anything that would help me, especially in swift. I'm aware that it is possible to create an array, append it with boolean , indexPath.row or currentTitle objects - then somehow use this array while scrolling the tableview. But the implementation isn't clear to me. Whats more difficult is that i have two buttons in one row.

Would appreciate any help on that subject.

Thank you.

The idea implemented in objc will look like this:

  1. Create an NSArray with size equals numbers of cells.

  2. Initialise it with objects like [NSNumber numberWithBOOL:NO] (or YES if you need pressed state) before you call [self.tableView reloadData];

  3. In method cellForRowAtIndexPath check if [array[indexPath.row] boolValue] is YES or NO and set button's state.

Hopes it will help.

There are lots of tutorials on table views. Like here . You need to separate the model of your data (like whether buttons have been pressed or not) from the view (the cells and buttons in the table). If this idea isn't clear, you'll want to look up MVC (model view controller) or MVVM (model view view-model).

The idea is that you have a record, for example in an array, of what all of the items in your table should look like, regardless of whether or not they're on the screen. When you need to show a cell, you overwrite its current state (since it is being recycled) with what it should be - based on the information in the array.

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