选择所有单元格的Swift 3.0多选

时间:2017-09-27 05:21:03

标签: ios iphone uitableview swift3

我在表格视图中添加了数据,并且我已经在第一个位置手动添加了“全选”选项,现在当用户选择第一个选项“全部选择”然后手动选择“全选”时未被选中。选择全部,点击然后工作所有人或取消选择工作但信号选择所有不工作的人“全选” 我已经尝试过下面的代码,但是它没有用,所以任何人都可以帮我解决这个问题吗?

enter image description here

var unchecked:Bool = true
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            // create a new cell if needed or reuse an old one
            let cell = ObjTableview.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SelectUserCell
            // set the text from the data model
             cell.selectionStyle = UITableViewCellSelectionStyle.none
            cell.lblStudentName.text = getStudentName[indexPath.row]

            if UnAll == "unselect" {
                if indexPath.row == 0 {
                    cell.btnCheckbox.setImage(UIImage(named: "unSelectedItem"), for: .normal)

                }
                if indexPath.row == Int(selectedNumber) {
                    cell.btnCheckbox.setImage(UIImage(named: "unSelectedItem"), for: .normal)

                }
                if indexPath.row == Int(unSelectNumber) {
                    //var j = "\(i)"

                    cell.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)

                }

            }else
            {
            if(unchecked){

                cell.btnCheckbox.setImage(UIImage(named: "unSelectedItem"), for: .normal)

            }
            else{

                cell.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)

              }
            }

            return cell
        }
        var UnAll = ""
        var selectedNumber = ""
        var unSelectNumber = ""
        var checkselect:Bool = true

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

            UnAll.removeAll()
            selectedNumber.removeAll()
            unSelectNumber.removeAll()
            if(indexPath.row == 0){

                btnCheckBoxClick(sender: UIButton())

            }else
            {
            UnAll = "unselect"
                btnCheckBoxClick(sender: UIButton())
                if checkselect {
                    selectedNumber = "\(indexPath.row)"
                    checkselect = false
                }else
                {
                  unSelectNumber = "\(indexPath.row)"
                    checkselect = true
                }

                print("the selected index is : \(indexPath.row)")
            }

        }

        @IBAction func btnCheckBoxClick(_ sender: Any) {   

            if(unchecked){

                unchecked = false
            }
            else{              
                unchecked = true
            }
            ObjTableview.reloadData()
         }

4 个答案:

答案 0 :(得分:8)

使用Bool属性为模型数据创建结构。您可以通过单元格选择来修改此属性。

simulator

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

  var allCharacters:[Character] = []

  override func viewDidLoad() {
    super.viewDidLoad()
        allCharacters = [Character(name: "All"),Character(name: "Luke Skywalker"),Character(name: "Leia Organa"),Character(name: "Advik Shah"),Character(name: "Aarav Modi")]

  }
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return allCharacters.count
  }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
    if cell == nil{
      cell = UITableViewCell(style: .subtitle, reuseIdentifier: "Cell")
    }
      cell?.textLabel?.text = allCharacters[indexPath.row].name
      if allCharacters[indexPath.row].isSelected
      {
        cell?.accessoryType = .checkmark
      }
      else
      {
        cell?.accessoryType = .none
      }
      cell?.selectionStyle = .none
    return cell!
  }
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.row == 0
    {
      allCharacters[indexPath.row].isSelected = !allCharacters[indexPath.row].isSelected
      for index in allCharacters.indices
      {
        allCharacters[index].isSelected = allCharacters[indexPath.row].isSelected
      }
    }
    else
    {
      allCharacters[indexPath.row].isSelected = !allCharacters[indexPath.row].isSelected
      if allCharacters.dropFirst().filter({ $0.isSelected }).count == allCharacters.dropFirst().count
      {
        allCharacters[0].isSelected = true
      }
      else
      {
        allCharacters[0].isSelected = false
      }
    }
    tableView.reloadData()
  }




}

struct Character
{
  var name:String
  //  var otherDetails
  var isSelected:Bool! = false
  init(name:String) {
    self.name = name
  }
}

从字典数组

创建Struct对象数组
let SubjectArray = json["students"] as! [[String:Any]]
allCharacters = SubjectArray.map({ Character(name: $0["studentName"] as! String) })
allCharacters.insert(Character(name:"All"), at: 0)

答案 1 :(得分:3)

我认为您在表格视图中只使用了一个部分。我建议你在表格视图中使用两个部分,这样第一部分只包含一行(全选),第二部分将包含其他选项。单击“全选”时,即在第一部分的第一行中,您可以在重新加载表视图时将第二部分中的所有行设置为已选中。

// MARK: -  struct for cell item
    struct CellItem {
    var name : String
    var isSelected:Bool! = false
    init(name: String) {
           self.name = name
         }
    }

class ViewController: UITableViewController {

@IBOutlet var viewTable: UITableView!
// Declare a boolean varaible to toggle the checkbox in the first section of table view
var isSelectAllSelected : Bool = false
var cellData: [CellItem] = []

override func viewDidLoad() {
    super.viewDidLoad()
    cellData = [CellItem(name: "Luke Skywalker"),CellItem(name: "Leia Organa"),CellItem(name: "Advik Shah"),CellItem(name: "Aarav Modi")]
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    return 2
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
         return 1
    }
    else
    {
        return cellData.count
    }
}

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 0
}

// MARK: -  Table view delegates

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 60

}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let cell = TableCell()
    cell.selectionStyle = .none

    if indexPath.section == 0 {
        cell.textLabel?.text = "Select All"
        if isSelectAllSelected{
            cell.accessoryType = .checkmark
        }
        else{
            cell.accessoryType = .none
        }

    }
    else
    {
        cell.textLabel?.text = cellData[indexPath.row].name
        if cellData[indexPath.row].isSelected{
            cell.accessoryType = .checkmark
        }
        else{
            cell.accessoryType = .none
        }

    }
    return cell
}


override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.section == 0
    {
        cellData[indexPath.row].isSelected = !cellData[indexPath.row].isSelected
        isSelectAllSelected = cellData[indexPath.row].isSelected
        for index in cellData.indices
        {
            cellData[index].isSelected = cellData[indexPath.row].isSelected
        }
    }
    else
    {
        cellData[indexPath.row].isSelected = !cellData[indexPath.row].isSelected
        if cellData.filter({ $0.isSelected }).count == cellData.count
        {
            isSelectAllSelected = true
        }
        else
        {
            isSelectAllSelected = false
        }

    }
    viewTable.reloadData()
} }

答案 2 :(得分:3)

我喜欢@Pranil建议在“All”行中使用单独的部分,所以我偷了它。

您可以使用NSMutableIndexSet跟踪所选行。这比必须创建一个新的结构或布尔数组或其他东西更简单。您需要注意的唯一事情是,如果您的tableview允许行重新排序,那么需要相应地调整索引集。

这是我的实施。 “all”状态由所选行的数量等于数据源数组中的行数确定。

我刚刚使用简单的表格视图附件作为复选标记,但我相信您可以在cellForRow(at:)

中看到如何采用基于图像的方法

导入UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableview: UITableView!


    let names: [String]? = ["Luke Skywalker","Leia Organa","Advik Shah","Aarav Modi"]

    var selectedRows = NSMutableIndexSet()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

    func numberOfSections(in tableView: UITableView) -> Int {

        return 2
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        guard let names = self.names else {
            return 0
        }

        return 0 == section ? 1 : names.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)

        var text: String
        var accessory = UITableViewCellAccessoryType.none

        if 0 == indexPath.section {
            text = "All"
            if self.selectedRows.count == self.names!.count {
                accessory = .checkmark
            }
        } else {
            text = names![indexPath.row]
            if selectedRows.contains(indexPath.row) {
                accessory = .checkmark
            }
        }

        cell.textLabel!.text = text
        cell.accessoryType = accessory

        return cell
    }

    func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        if indexPath.section == 0 {
            if self.selectedRows.count == self.names!.count {
                self.selectedRows = NSMutableIndexSet()
            } else {
                self.selectedRows = NSMutableIndexSet(indexesIn: NSRange(location: 0, length: self.names!.count))
            }
            tableView.reloadData()
        } else {
            self.selectedRows.contains(indexPath.row) ? self.selectedRows.remove(indexPath.row) : self.selectedRows.add(indexPath.row)

            let rows = [IndexPath(row: 0, section: 0), indexPath]

            tableView.reloadRows(at: rows, with: .none)
        }
        return nil
    }
}

答案 3 :(得分:2)

您好,您可以使用addtarget方法在视图控制器内部使用cheboxbutton动作方法并分配标记indexpath.row,这样您就可以轻松获取索引路径。从下面的代码你可以得到这个想法。

class ViewController:UIViewController,UITableViewDelegate,UITableViewDataSource {

@IBOutlet weak var ObjTableview: UITableView!
var arrStudent = ["1","2","3","4","5"]
var arrSelectedStudent :[Int] = []
var selectAll:Bool = false

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

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


//MARK: UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arrStudent.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // create a new cell if needed or reuse an old one
    let cell = ObjTableview.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SelectUserCell
    // set the text from the data model
    cell.selectionStyle = UITableViewCellSelectionStyle.none
   // cell.lblStudentName.text = getStudentName[indexPath.row]
    cell.lblStudentName.text = arrStudent[indexPath.row]
    cell.btnCheckbox.tag = indexPath.row
   cell.btnCheckbox.addTarget(self, action:#selector(btnCheckBoxClick(sender:)), for: .touchUpInside)


    if selectAll {
        cell.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
    }else{
    if arrSelectedStudent.contains(indexPath.row){
        cell.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
    }else{
        cell.btnCheckbox.setImage(UIImage(named: "unSelectedItem"), for: .normal)
    }
    }

         return cell
}


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
 }

func btnCheckBoxClick(sender: UIButton) {
    if sender.tag == 0{
        selectAll = true
    }else
    {
        selectAll = false
    if let index = arrSelectedStudent.index(of: sender.tag) {
        arrSelectedStudent.remove(at: index)
    }else{
        arrSelectedStudent.append(sender.tag)
    }
    }

    ObjTableview.reloadData()
}}