SegmentedControl 隐藏和显示 TableView 单元格

SegmentedControl hide and show TableView cells

我正在开发一个锻炼应用程序,用户可以使用 UISwitch 来设置锻炼是否处于活动状态。我有一个分段控制器,用于切换显示 "All" 或仅显示 "Active".

是否可以在我的 UISegmentedControl 操作中使用此 属性 获取特定单元格?

我的代码如下所示:

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 20
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCellWithIdentifier("ChallengeCell") as? ChallengeListCell {
        cell.setTitle("Utmaning " + String(indexPath.row + 1))
        let active = indexPath.row % 3 == 0 || indexPath.row % 5 == 0
        cell.setActive(active)
        if active {
            cell.setCompleted((Double(indexPath.row % 5) + Double(indexPath.row % 3)) / 6.0)
        }
        else {
            cell.setCompleted(0)
        }
        return cell
    }
    return UITableViewCell()
}

我的 SegmentedControl 函数如下所示:

@IBAction func segmentedControlChanged(sender: UISegmentedControl) {
    let selectedSegment = segmentedControl!.selectedSegmentIndex
    switch selectedSegment{
    case 0: //SHOW ALL
        print("Selected 0")
    case 1:  //SHOW ONLY ACTIVE
        print("Selected 1")
    //case 2: //NOT ACTIVE
        //print("Selected 2")
    default:
        print(sender)
    }
}

所有这些都在同一个控制器中。

您应该有三个数据源数组:例如 allItems activeItemsinactiveItems,并在它们之间切换。

tableView 委托中检查使用 segmentedControl 选择的段并使用正确的数组作为数据源。

segmentedControlChanged 中调用 self.tableView.reloadData() 并使用所选段设置变量。

一种方法是跟踪数组中 "Active" 单元格的索引路径,该数组是视图控制器的实例 属性。比起切换分段控制器时,您可以通过查看数组来确定 table 视图中要 remove/add 的单元格。

另一个想法是在保存每个 table 视图单元格数据的模型对象上有一个活动的 属性。切换分段控件时,您可以遍历所有这些对象以确定它们是否 "Active" 并相应地进行。

从您提供的代码来看,我的第一个建议听起来是最合适的。