简体   繁体   English

如何从UITableViewCell中的自定义按钮触发操作

[英]How to trigger an action from a custom button in UITableViewCell

I've created a subclass of UIButton to allow me to have a checkbox on the iPhone. 我创建了UIButton的子类,以允许我在iPhone上有一个复选框。 This checkbox is part of a subclass of UITableViewCell . 此复选框是UITableViewCell的子类的一部分。 My question is how I can attach an action to the button being pressed and have that method implemented in the table view controller? 我的问题是如何将动作附加到按下的按钮上,并在表格视图控制器中实现该方法?

I tried using the addTarget:action: method but this doesn't seem to work. 我尝试使用addTarget:action:方法,但这似乎不起作用。 One option is to use the App Delegate but this isn't good programming practice. 一种选择是使用App Delegate,但这不是好的编程习惯。

Well, I did implemented the same functionality. 好吧,我确实实现了相同的功能。 Here is how I implemented it. 这是我的实现方法。

  1. Created a custom cell. 创建一个自定义单元格。

  2. Implement button action in cell class only. 仅在单元格类中实现按钮操作。

  3. Declare a protocol(CustomCellDelegate) in cell & create a delegate(CustomCellDelegate) property ofcell. 在单元格中声明协议(CustomCellDelegate)并创建单元格的委托(CustomCellDelegate)属性。

  4. In cellForRowAtIndexPath: method of your table view controller set table view controller(self) to delegate property of cell. 在cellForRowAtIndexPath中:表格视图控制器的方法将表格视图控制器(自身)设置为委托单元格的属性。

  5. Implement delegates in view controller. 在视图控制器中实现委托。

  6. Call delegate methods from button action method in cell. 从单元格中的按钮操作方法调用委托方法。

Let me know whether you understood it or I need to post some code. 让我知道您是否了解它,或者我需要发布一些代码。

Make sure the button receives the touch event. 确保按钮接收到触摸事件。 You could check this by overriding 您可以通过覆盖进行检查

- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event

or 要么

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

Log something or set a breakpoint on either of those. 记录一些内容或在其中任何一个上设置断点。 If your button is not receiving touches (which I think it doesn't) try setting exclusiveTouch on the TableView and/or the TableViewCell to NO. 如果您的按钮不接收触摸(我认为它不)尝试设置exclusiveTouch上的TableView和/或TableViewCell为NO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM