作者:somnus | 来源:互联网 | 2023-02-05 16:17
我有一个具有xib的自定义单元格,该单元格包含一个按钮,当按下按钮时,我想执行一个操作,但不是在我的自定义单元格类内部,而是从包含自定义单元格的viewviewler的内部请帮忙?
1> Jaafar Barek..:
首先,您应该编写一个协议,例如:
protocol CustomCellDelegate {
func doAnyAction(cell:CustomUITableViewCell)
}
然后在您的自定义单元格类中声明:
weak var delegate:CustomCellDelegate?
并在自定义单元类的IBAction中:
@IBAction func onButtonTapped(_ sender: UIButton) {
delegate?.doAnyAction(cell: self)
//here we say that the responsible class for this action is the one that implements this delegate and we pass the custom cell to it.
}
现在在您的viewController中:
1-使您的视图控制器实现CustomCellDelegate。2-在您的cellForRow声明单元格时,不要忘了写:
cell.delegate = self
3-最后在您的ViewController中调用该函数:
func doAnyAction(cell: CustomUITableViewCell) {
let row = cell.indexPath(for: cell)?.row
//do whatever you want
}
}