2016-03-18 137 views
0

我正在開發一個練習應用程序,用戶可以使用UISwitch來設置練習是否處於活動狀態。我有一個分段控制器,用於切換顯示「全部」或僅顯示「活動」。SegmentedControl隱藏和顯示TableView單元格

是否有可能在我的UISegmentedControl Action中獲取具有此屬性的特定單元格?

我的代碼如下所示:

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) 
    } 
} 

所有這一切都是在同一個控制器。

回答

0

您應該有三個數據源陣列:例如allItemsactiveItemsinactiveItems,並在它們之間切換。

tableView內部,代表檢查使用segmentedControl選擇的段,並使用正確的數組作爲數據源。

裏面segmentedControlChanged調用self.tableView.reloadData()並設置一個變量與選定的段。

+0

工作出色,你的想法。謝謝! – Fredrik

0

一種方法是跟蹤數組中的「活動」單元的索引路徑,該數組是該視圖控制器的實例屬性。與分段控制器切換時相比,您可以通過查看數組來確定要從表視圖中刪除/添加的單元格。

另一個想法是在保存每個表視圖單元格的數據的模型對象上具有活動屬性。當分段控件切換時,您可以迭代所有這些對象以確定它們是否爲「活動」並相應地繼續。

從您提供的代碼中,聽起來像我的第一個建議是最合適的。

+0

謝謝你的回答,我會檢查一下! – Fredrik