Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use IBAction from UIButton inside custom cell in main view controller

I have created a custom cell with its own .m, .h and .xib file. In the cell, I have a UIButton that I added to the xib in IB.

I can receive the IBAction from the UIButton in this custom cell's .m, but really, I'd like to be forwarding that button press to the main view .m that is hosting the table (and so custom cell) and use an action there.

I've spent the last 4 hours attempting various ways of doing this - should I be using NSNotificationCenter? (I've tried Notifications lots but can't get it to work and not sure if i should be persevering)

like image 828
James Morris Avatar asked May 11 '12 17:05

James Morris


1 Answers

You need to use delegate in .h file of cell. Declare the delegate like this

@class MyCustomCell;
@protocol MyCustomCellDelegate
- (void) customCell:(MyCustomCell *)cell button1Pressed:(UIButton *)btn;
@end

then declare field and property

@interface MyCustomCell:UItableViewCell {
    id<MyCustomCellDelegate> delegate;
}

@property (nonatomic, assign) id<MyCustomCellDelegate> delegate;

@end

in .m file

@synthesize delegate;

and in button method

- (void) buttonPressed {
    if (delegate && [delegate respondToSelector:@selector(customCell: button1Pressed:)]) {
        [delegate customCell:self button1Pressed:button];
    }
}

Your view controller must adopt this protocol like this

.h file

#import "MyCustomCell.h"

@interface MyViewController:UIViewController <MyCustomCellDelegate>
.....
.....
@end

in .m file in cellForRow: method you need add property delegate to cell

cell.delegate = self;

and finally you implement the method from protocol

- (void) customCell:(MyCustomCell *)cell button1Pressed:(UIButton *)btn {

}

Sorry for my english, and code. Wrote it from my PC without XCODE

like image 86
Moonkid Avatar answered Oct 21 '22 20:10

Moonkid