我有一个 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/