我有一个自定义单元格,它有一个xib,这个单元格包含一个按钮,当按钮被按下时,我想做一个动作,但不是在我的自定义单元格类中,而是从包含自定义单元格的表格视图的视图控制器中,有什么帮助吗?
发布于 2017-04-26 15:20:22
首先,您应该编写一个协议,例如:
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 = self3-最后在视图控制器中调用函数:
func doAnyAction(cell: CustomUITableViewCell) {
let row = cell.indexPath(for: cell)?.row
//do whatever you want
}
}发布于 2017-04-26 15:28:46
你可以使用委托模式。创建自定义协议。
protocol CustomTableViewCellDelegate {
func buttonTapped() }和表视图单元格一致委托
class CustomTableViewCell: UITableViewCell {
var delegate: CustomTableViewCellDelegate!
@IBAction func buttonTapped(_ sender: UIButton) {
delegate.buttonTapped()
} }表视图数据源
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as! CustomTableViewCell
cell.delegate = self
return cell
}从表视图控制器或视图控制器中确认协议(委托)
extension TestViewController: CustomTableViewCellDelegate {
func buttonTapped() {
print("do something...")
} }发布于 2017-04-26 15:16:28
只需在您的cellForRowAtIndexpath中获取UIButton即可。然后编写以下代码。
button.addTarget(self, action:#selector(buttonAction(_:)), for: .touchUpInside).
func buttonAction(sender: UIButton){
//...
} https://stackoverflow.com/questions/43627355
复制相似问题