[英]ios - How to get label value from table cell by click button in table cell?
我有一个UITableView,在每个单元格中都有一些标签和一个按钮。 我想在单击按钮时获取所有标签值。 这个怎么做? 谢谢。
为单元格自定义类中的按钮创建IBAction
方法,并在其中打印
print("label text : \(self.lbl.text)")
或者使用委托将该值发送到包含tableView的VC
首先。 您应该有一个要用于加载label值的模型对象。 采用
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {}
要获取索引,然后尝试使用索引从模型中获取值,例如,您有一个数组myArray
则可以使用myArray[indexPath.row]
访问该值以获取该值。 然后保存,传递并在需要的地方使用它。 然后在您的自定义表格单元类中通过传递indexPath来实现一个委托方法。 然后使用tableView.reloadRows(at: [IndexPath(item:0,section:0)], with: .fade)
刷新单元格。
您可以通过关闭或委托来完成
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.委托
这样创建一个委托方法
protocol CustomCellDelegate {
func getCustomObject(in cell: CustomCell, withCustomObject object: CustomObject)
}
现在在您的单元格类中添加委托变量
var delegate: CustomCellDelegate?
然后在您的操作按钮内部添加此
@IBAction func replyAction(_ sender: Any) {
if let customObject = customObject {
delegate.getCustomObject(in: self, withCustomObject: customObject)
}
}
现在最后一部分上课了,您实现了表格视图,并将其显示到
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! YourCustomCell
// add this
cell.delegate = self
}
在类内部,您应该添加委托方法
extension YourClass: CustomCellDelegate {
getCustomObject(in cell: CustomCell, withCustomObject object: CustomObject) {
print("current cell data = \(CustomObject)"
}
}
这也可以做
希望这会有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.