Bart
Bart

Reputation:

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. This checkbox is part of a subclass of 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. One option is to use the App Delegate but this isn't good programming practice.

Upvotes: 4

Views: 1543

Answers (2)

Rahul Wakade
Rahul Wakade

Reputation: 4805

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.

  4. In cellForRowAtIndexPath: method of your table view controller set table view controller(self) to delegate property of cell.

  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.

Upvotes: 2

klaaspieter
klaaspieter

Reputation: 2665

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.

Upvotes: 0

Related Questions