UITableViewCellbutton与行动
您好我有一个自定义UITableViewCell与三个button来处理购物车function,加号,减号和删除button,我需要知道哪个单元格已被触摸。
我已经尝试使用“标签解决scheme”,但由于单元的生命周期而不工作。
任何人都可以请帮我find一个解决scheme?
提前致谢
我正在使用UITableViewCell的子类中的单元委托方法来解决这个问题。
快速浏览:
1) 创build一个协议
protocol YourCellDelegate : class { func didPressButton(_ tag: Int) }
2) 子类你的UITableViewCell
(如果你还没有这样做):
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
协议。
class YourViewController: ..., YourCellDelegate { ... }
4)在单元格被定义之后(重用) 设置一个委托 。
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! YourCell cell.cellDelegate = self cell.tag = indexPath.row
5)在相同的控制器(你实现的UITableView委托/数据源在哪里), 从YourCellDelegate
协议放一个方法 。
func didPressButton(_ tag: Int) { print("I have pressed a button with a tag: \(tag)") }
现在,您的解决scheme不是标签/数量相关的。 您可以根据需要添加尽可能多的button,因此无论您想要安装多less个button,都可以通过委托获取响应。
这个协议委托解决scheme在iOS逻辑中是首选,它可以用于表格单元中的其他元素,如UISwitch
, UIStepper
等。
在将IBOutlet私有化之后,我也遇到了同样的问题,这是社区广泛提出的。
这是我的解决scheme:
<在你的细胞类>
protocol YourCellDelegate: class { func didTapButton(_ sender: UIButton) } class YourCell: UITableViewCell { weak var delegate: YourCellDelegate? @IBAction func buttonTapped(_ sender: UIButton) { delegate?.didTapButton(sender) } }
<在你的ViewController>中
class ViewController: UIViewController, YourCellDelegate { func didTapButton(_ sender: UIButton) { if let indexPath = getCurrentCellIndexPath(sender) { item = items[indexPath.row] } } func getCurrentCellIndexPath(_ sender: UIButton) -> IndexPath? { let buttonPosition = sender.convert(CGPoint.zero, to: tableView) if let indexPath: IndexPath = tableView.indexPathForRow(at: buttonPosition) { return indexPath } return nil } }
您还可以使用tableViewCell视图的层次结构来获取选定的button索引。
使用以下步骤:
-
将select器添加到tableview的cellForRowAtIndexpath:
btn?.addTarget(self, action:#selector(buttonPressed(_:)), for:.touchUpInside)
2。 使用以下方法获取indexPath:
func buttonPressed(_ sender: AnyObject) { let button = sender as? UIButton let cell = button?.superview?.superview as? UITableViewCell let indexPath = tblview.indexPath(for: cell!) print(indexPath?.row) }
- KVO修改由NSMutableArray支持的NSArray的通知
- 使用CALayer将对angular横幅/徽章添加到UITableViewCell的angular落
- unit testing时无法find枚举描述符PBFieldDescriptorProto_Label
- 无法使用导航控制器在视图控制器上locking设备方向
- 我可以在属于生活在世界其他地方的某个人的iOS设备上测试应用吗?
- StageWebViewDisk中断iPad上的file upload(iOS?)
- 如何启动设备types的特定视图
- 我怎样才能获得我在iPhone录制的audio的时间?
- 在XCTest UI Testing中,如何检查按钮,标签,视图的背景颜色?