如何从tableview获取已检查的单元格?

时间:2017-03-06 06:24:44

标签: ios uitableview swift3

我设法创建了单元格并让它们检查选择和取消选择。如何获取单元格的字符串名称以及如何在单击按钮时选中或取消选中它们。比如说,如果我想只获取已检查的单元格并在单击按钮时将它们保存到数据库中,下次打开tableview时应该选择/取消选择它们。

import UIKit


class CellsViewController: UITableViewController {


    // Creating cells with code

    let activities = ["Jumping", "History", "Reading", "Football", "Nightlife", "Hiking", "Spa"]

    // Function to figure out how many rows we need depending on the lenght of the list
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return activities.count
    }

    // returns the cell name and puts it in the table view controller
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = activities[indexPath.row]
        return cell
    }
    // checks and unchecks the given cell based on user click
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCellAccessoryType.checkmark{
            tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.none
        }else{
            tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark


        }
    }



    @IBAction func saveButton(_ sender: Any) {
        // Retrieve the checked cells and do something
        // With them once the button is clicked

    }



    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



}

1 个答案:

答案 0 :(得分:0)

//嗨,给那个按钮添加标签,使用那个标签你需要在表数据源数组中选择数据

let activities = [["name": "Jumping", "isSelected": "NO"], ....]
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = activities[indexPath.row]["name"]
    cell.btnSelect.tag = indexPath.row
    if activities[indexPath.row]["name"] as String == "Yes" {
       cell.btnSelect.isSelected = true
    } else {
        cell.btnSelect.isSelected = false
    }
    return cell
}

  @IBAction func saveButton(_ sender: Any) {
    // Retrieve the checked cells and do something
    // With them once the button is clicked
    saveButton.isSelected = !saveButton.isSelected 
   let dicdetails = activities[sender.tag]
   if saveButton.isSelected {
      dicdetails["isSelected"] = "YES"
   } else {
     dicdetails["isSelected"] = "No"
   }
   activities[sender.tag] = dicdetails
}