简体   繁体   English

在自定义单元格Swift中保存uibutton状态

[英]Saving uibutton state in custom cell Swift

I have a custom cell with two uibuttons . 我有一个带有两个uibuttonscustom cell Click on one of the buttons appends rows also based on a custom cell with two uibuttons . 单击按钮之一,也会基于具有两个uibuttons的自定义单元格追加行。

Once the button is clicked i'm changing it's alpha to 50% and the boolean isPressed is set to true. 单击按钮后,我将其alpha更改为50%,并将布尔值isPressed设置为true。 So the next time user presses the button it would produce an alert view with error. 因此,下次用户按下按钮时,将产生一个带有错误的alert view

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. 我知道可以创建一个数组,将其附加booleanindexPath.rowcurrentTitle对象-然后在滚动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: 在objc中实现的想法将如下所示:

  1. Create an NSArray with size equals numbers of cells. 创建一个大小等于单元数的NSArray。

  2. Initialise it with objects like [NSNumber numberWithBOOL:NO] (or YES if you need pressed state) before you call [self.tableView reloadData]; 在调用[self.tableView reloadData];之前,用[NSNumber numberWithBOOL:NO]类的对象(如果需要按状态,则为YES )进行初始化[self.tableView reloadData];

  3. In method cellForRowAtIndexPath check if [array[indexPath.row] boolValue] is YES or NO and set button's state. cellForRowAtIndexPath方法中,检查[array[indexPath.row] boolValue]是否为YES或NO,并设置按钮的状态。

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). 如果这个想法不清楚,您将需要查找MVC(模型视图控制器)或MVVM(模型视图视图模型)。

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. 当需要显示一个单元格时,可以根据数组中的信息用它应该的状态覆盖它的当前状态(因为它正在回收)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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