如何在Swift 3中一一启用和禁用表视图单元格

时间:2018-08-02 06:16:46

标签: swift

我是iOS的新手,我面临有关启用和禁用UITableView单元格按钮的问题。我想启用第一个单元格按钮并禁用其他单元格按钮。当我单击第一个单元格按钮时,第二个单元格按钮将启用。

2 个答案:

答案 0 :(得分:0)

我认为这对您很有帮助。对我来说有用。

在这里,我们为可点击的索引声明全局变量。

  var clickableIndexPath = 0

我们在这里调用tableView必需的方法。

extension ViewController: UITableViewDelegate, UITableViewDataSource {
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 50
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! UITableViewCell
    cell.checkButton.isEnabled = indexPath.row == clickableIndexPath
    cell.checkButton.addTarget(self, action:#selector(buttonTapped(_ :)), for: .touchUpInside)
    return cell
  }
}

这里tableView单元格按钮动作单击事件。

  @objc func buttonTapped(_ sender: UIButton) {
    let buttonPostion = sender.convert(sender.bounds.origin, to: tableView)
    if let indexPath = tableView.indexPathForRow(at: buttonPostion) {
      clickableIndexPath =  indexPath.row + 1
      tableView.reloadData()
    }
  }

答案 1 :(得分:0)

        In tableView, there is one delegate called 
    var IndexToSelect = [0]
         func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! UITableViewCell

        cell.btn.tag = indexPath.row

        cell.checkButton.addTarget(self, action:#selector(btnTapped(_ :)), for: .touchUpInside)

        if IndexToSelect.contains(indexPath.row){
        cell.btn.isHidden = true
        or
        cell.btn.isUserInteraction = false
        }else{
        cell.btn.isHidden = false
        or
        cell.btn.isuserinteraction = true
        }
            return cell
        }

        //Do it here what you want
        @objc func btnTapped(_ sender: UIButton) {
            if sender.tag == 0{
            IndexToSelect = []
            IndexToSelect.append(sender.tag + 1)
            tableView.reloadData()
            }else{
            return
            }
         }