UITableViewCell带有动作的按钮 [英] UITableViewCell Buttons with action
问题描述
您好我有一个自定义UITableViewCell,带有三个按钮来处理购物车功能,Plus,减号和删除按钮,我需要知道哪个单元格已被触摸。
Hi I have a custom UITableViewCell with three buttons to handle a shopping cart function, Plus,Minus and Delete button and I need to know which cell has been touched.
我已经尝试使用标签解决方案,但由于单元的生命周期,它无法正常工作。
I've already tried to use the "tag solution" but it isn't working due to the lifecycle of the cells.
有谁可以帮我找一个解决方案?
Can anyone please help me find a solution?
提前致谢
推荐答案
我是在UITableViewCell的子类中使用单元委托方法解析它。
I was resolving this using a cell delegate method within UITableViewCell's subclass.
快速概述:
1) 创建协议
protocol YourCellDelegate : class {
func didPressButton(_ tag: Int)
}
2) Subclass 您的 UITableViewCell
(如果您还有)这样做了):
2) Subclass your UITableViewCell
(if you haven't done so):
class YourCell : UITableViewCell
{
weak var cellDelegate: YourCellDelegate?
// connect the button from your cell with this method
@IBAction func buttonPressed(_ sender: UIButton) {
cellDelegate?.didPressButton(sender.tag)
}
...
}
3) 让您的视图控制器符合上面实现的 YourCellDelegate
协议。
3) Let your view controller conform to YourCellDelegate
protocol that was implemented above.
class YourViewController: ..., YourCellDelegate { ... }
4) 设置代理,在定义单元格后(重复使用)。
4) Set a delegate, after the cell has been defined (for reusing).
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! YourCell
cell.cellDelegate = self
cell.tag = indexPath.row
5)在同一个控制器中(您实现的UITableView委托/数据源),从 YourCellDelegate
协议中放入一个方法。
5) In the same controller (where is your implemented UITableView delegate/datasource), put a method from YourCellDelegate
protocol.
func didPressButton(_ tag: Int) {
print("I have pressed a button with a tag: \(tag)")
}
现在,您的解决方案不是标签/号码依赖。您可以根据需要添加任意数量的按钮,因此无论您要安装多少个按钮,都可以通过委托获得响应。
Now, your solution is not tag / number dependent. You can add as many buttons as you want, so you are ready to get response via delegate regardless how many buttons you want to install.
此协议委托解决方案是首选在iOS逻辑中,它可用于表格单元格中的其他元素,如 UISwitch
, UIStepper
,依此类推。
This protocol-delegate solution is preferred in iOS logic and it can be used for other elements in table cell, like UISwitch
, UIStepper
, and so on.
这篇关于UITableViewCell带有动作的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!