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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/417685.html
標籤:
上一篇:如何洗掉貓鼬中所有集合的所有檔案
