ios - 如何通过单击表格单元格中的按钮从表格单元格获取标签值?

标签 ios swift uitableview

我有一个 UITableView,在每个单元格中都有一些标签和一个按钮。我想在单击按钮时获取所有标签值。这个怎么做?谢谢。

最佳答案

你可以通过闭包或委托(delegate)来完成

1:关闭

在你的 tableViewCell 类中创建一个像这样的变量

customObject是你传给tableviewCell加载数据的对象

var cellData: customObject? {

    didSet {
        // do your loding labels in here
    }
}

var clickHandler: ((customObject) -> Void)!

在你的操作按钮里面添加这个

 @IBAction func replyAction(_ sender: Any) {
    if let customObject = customObject {
        clickHandler(customObject)
    }
}

现在转到表的双端队列

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

   // add this
   cell.clickHandler = { customObject in 

   print("myCell.customObject = \(customObject)")

   }
}

这会变魔术

<强>2。代表团

像这样创建一个委托(delegate)方法

protocol CustomCellDelegate {
    func getCustomObject(in cell: CustomCell, withCustomObject object: CustomObject)
}

现在在你的单元格类中添加委托(delegate)变量

 var delegate: CustomCellDelegate?

在你的操作按钮里面添加这个

@IBAction func replyAction(_ sender: Any) {
    if let customObject = customObject {
        delegate.getCustomObject(in: self, withCustomObject: customObject)
    }
}

现在在类的最后一部分,你实现了表格 View ,并将其显示在它显示的地方

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

   // add this
   cell.delegate = self
}

在类内部你应该添加委托(delegate)方法

extension YourClass: CustomCellDelegate {

    getCustomObject(in cell: CustomCell, withCustomObject object: CustomObject) {
         print("current cell data = \(CustomObject)"
    }

}

这也能完成工作

希望这会有所帮助

关于ios - 如何通过单击表格单元格中的按钮从表格单元格获取标签值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49160475/

相关文章:

iphone - 未调用 didSelectRowAtIndexPath。 UITableViewController 子类化

ios - 如何为开发设置推送通知?

ios - 由于条件绑定(bind)错误的初始化程序,无法将文本 append 到字符串数组

swift - IBDesignable View - 在设计时需要 ViewController

swift - 如何声明具有比父类(super class)更多参数的子类指定初始值设定项?

android - 是否可以使用 google places textsearch api 从纬度和经度获取格式化地址?

ios - 与 UITableView 重叠的静态单元格

ios [__NSCFNumber 长度] : unrecognized selector sent to instance

swift - 如何使用 Overlay Swift 从底部菜单创建向上滑动

ios - 在 ios 7 中使用 UIScrollView 在 iOS 中创建水平滚动 UIButton