拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 tableview如何附加到空阵列检查单元格?

tableview如何附加到空阵列检查单元格?

白鹭 - 2022-02-10 1985 0 0
class Cell: UITableViewCell {

    @IBOutlet weak var checkBtn     : UIButton!


    @IBAction func selectButton(_ sender: UIButton) {
        if checkBtn.isSelected == false {
            checkBtn.isSelected = true
        } else {
            checkBtn.isSelected = false
        }
    }
}

我有一个单元班。但是 IBAction 不起作用。

我还制作了一个如下所示的 ViewController

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)   -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "exampleCell") as! Cell

    if cell.checkBtn.isSelected == true {
            anEmptyArray.append(myTableViewData[indexPath.row])
        } else {

        }

}

如何获得选定的单元格?

uj5u.com热心网友回复:

您可以使用下面的表格视图委托方法,下面是代码。


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
     anEmptyArray.append(myTableViewData[indexPath.row])
}

还要确保您的方法中有以下代码行viewDidLoad

 tableView.delegate = self

使用这种方法,您只需选择单元格。就这样。

另一种方法

您需要创建新的委托。

protocol TableViewCellDelegate: AnyObject {
   func didSelect(cell: YourTableViewCell) // Don't need to define just declare.
}

现在在类中创建一个委托实体UITableViewCell,并在按钮操作中呼叫方法。

class Cell: UITableViewCell {

    @IBOutlet weak var checkBtn     : UIButton!
    weak var delegate: TableViewCellDelegate? // Instance of Delegate protocol


    @IBAction func selectButton(_ sender: UIButton) {
        if checkBtn.isSelected == false {
            checkBtn.isSelected = true
        } else {
            checkBtn.isSelected = false
        }
        
        self.delegate?.didSelect(cell: self) // triggering the delegate method. 
    }
}

现在将触发哪个代码?我们需要定义它。例如,转到您的 UITableViewController,并扩展该类

extension YourTableViewController: TableViewCellDelegate {
     func didSelect(cell: YourTableViewCell) {
       // Now you have the cell, and you can get the indexPath of this cell
         if let indexPath = tableView.indexPath(for: cell) {
            // Now you have indexPath and you know the drill.
             

            // If you want to remove that cell delete that value from array and reload tableView.
            
            myTableViewData.remove(at: indexPath.row)
            tableView.reloadData()

            
         }
     }
}

不要忘记像下面那样制作 YourTableViewController 的单元格委托。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)   -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "exampleCell") as! YourTableViewCell

    cell.delegate = self

}
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *