iOS Swift:维护单元格中的切换按钮状态



>我在单元格中有一个按钮作为切换按钮,用于签到俱乐部的成员。当我签入成员时,我需要按钮的状态在滚动后保持打开状态,但它会关闭。下面是 cellForRow 方法:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = self.membersTableVw.dequeueReusableCell(withIdentifier: "CellMembersForCoach", for: indexPath) as! CellMembersForCoach
    let member = members[indexPath.row]
    cell.setMember(member)
    cell.cellController = self
    return cell
}

这是我切换按钮的自定义单元格类中的部分

@IBOutlet weak var checkBtn: UIButton!
@IBAction func setAttendance(_ sender: Any){
    // toggle state
    checkBtn.isSelected = !checkBtn.isSelected
}

切换有效,但在滚动表格后,按钮状态更改回原始状态。任何建议不胜感激。

发生这种情况是因为您正在重用单元格。

您需要跟踪选择了哪些单元格。也许在您的成员的班级中。然后,当您在cellForRowAt中时,您应该检查之前是否选择了此单元格,并为按钮设置正确的状态。

这是因为表视图正在重用您的单元格。 因此,您必须根据表视图数据源维护按钮。

Shamas强调了一种正确的方法,所以我将分享我的整个解决方案。

我创建了一个单例类来存储一组检查单元格:

class Utility {
// Singleton
private static let _instance = Utility()
static var Instance: Utility{
    return _instance
}
 var checkedCells = [Int]()

在自定义单元格类中,我有连接到检查按钮的操作方法以添加和删除选中的单元格:

@IBOutlet weak var checkBtn: UIButton!
@IBAction func setAttendance(_ sender: Any){
    // Get cell index
    let indexPath :NSIndexPath = (self.superview! as! UITableView).indexPath(for: self)! as NSIndexPath
    if !checkBtn.isSelected{
       Utility.Instance.checkedCells.append(indexPath.row)
    }else{
        // remove unchecked cell from list
        if let index = Utility.Instance.checkedCells.index(of: indexPath.row){
            Utility.Instance.checkedCells.remove(at: index)
        }
    }
    // toggle state
    checkBtn.isSelected = !checkBtn.isSelected
}

在视图控制器的cellForRowAt方法中,我检查单元格行是否在数组中,并决定是否应选中切换按钮:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = self.membersTableVw.dequeueReusableCell(withIdentifier: "CellMembersForCoach", for: indexPath) as! CellMembersForCoach
    if Utility.Instance.checkedCells.contains(indexPath.row){
        cell.checkBtn.isSelected = true
    }
    return cell
}

问题就在这里:

checkBtn.isSelected = !checkBtn.isSelected

每次调用委托cellForRowAt时,此代码将反映每次配置单元格时按钮选择状态。因此,如果您之前选择了它,现在它将变为未选择。

由于 tableView 正在重用您编码的单元格,因此无法正常工作。您必须在选择时跟踪每个按钮,并在滚动时重用单元格时再次设置它。解决方案:您可以采用一个数组(包含布尔值(,它是表视图数据的大小。因此,您必须使用数组设置按钮的状态,并在选择或取消选择时更新数组。

最新更新