首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在我的viewController中执行自定义UITableViewCell的操作?

如何在我的viewController中执行自定义UITableViewCell的操作?
EN

Stack Overflow用户
提问于 2017-04-26 15:12:55
回答 5查看 1.6K关注 0票数 4

我有一个自定义单元格,它有一个xib,这个单元格包含一个按钮,当按钮被按下时,我想做一个动作,但不是在我的自定义单元格类中,而是从包含自定义单元格的表格视图的视图控制器中,有什么帮助吗?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2017-04-26 15:20:22

首先,您应该编写一个协议,例如:

代码语言:javascript
复制
protocol CustomCellDelegate {
  func doAnyAction(cell:CustomUITableViewCell)
}

然后在您的自定义单元格类中声明:

代码语言:javascript
复制
weak var delegate:CustomCellDelegate?

在自定义单元格类中的IBAction中:

代码语言:javascript
复制
@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中声明单元格时,不要忘了写:

代码语言:javascript
复制
cell.delegate = self

3-最后在视图控制器中调用函数:

代码语言:javascript
复制
func doAnyAction(cell: CustomUITableViewCell) {
    let row = cell.indexPath(for: cell)?.row
  //do whatever you want

    }
}
票数 7
EN

Stack Overflow用户

发布于 2017-04-26 15:28:46

你可以使用委托模式。创建自定义协议。

代码语言:javascript
复制
protocol CustomTableViewCellDelegate {
func buttonTapped() }

和表视图单元格一致委托

代码语言:javascript
复制
class CustomTableViewCell: UITableViewCell {
var delegate: CustomTableViewCellDelegate!

@IBAction func buttonTapped(_ sender: UIButton) {
    delegate.buttonTapped()
} }

表视图数据源

代码语言:javascript
复制
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as! CustomTableViewCell
    cell.delegate = self
    return cell
}

从表视图控制器或视图控制器中确认协议(委托)

代码语言:javascript
复制
extension TestViewController: CustomTableViewCellDelegate {
func buttonTapped() {
    print("do something...")
} }
票数 4
EN

Stack Overflow用户

发布于 2017-04-26 15:16:28

只需在您的cellForRowAtIndexpath中获取UIButton即可。然后编写以下代码。

代码语言:javascript
复制
button.addTarget(self, action:#selector(buttonAction(_:)), for: .touchUpInside). 

func buttonAction(sender: UIButton){
   //...
} 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43627355

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档