Kex Kex - 24 days ago 6
iOS Question

Custom delegate not calling UITableViewController method

I have a custom UIButton class like below :

.h

#import <UIKit/UIKit.h>

@class FriendButton;
@protocol LongPressedButtonDelegate
- (void)buttonIsLongPressed:(FriendButton *)button;
@end

@interface FriendButton : UIButton
@property (nonatomic, weak) id<LongPressedButtonDelegate > delegate;
@end


.m

@implementation FriendButton




//this is called from the interface builder
-(id) initWithCoder:(NSCoder *)aDecoder {

self = [super initWithCoder:(NSCoder *)aDecoder];
NSLog(@"init called");
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
[self addGestureRecognizer:longPress];

return self;

}

-(void)longPress:(id)sender {
NSLog(@"long press");
[self.delegate buttonIsLongPressed:self];
}

@end


My buttons are set up in the interface builder, they are contained in a UITableView cell. In my UITableViewController I have :

-(void)buttonIsLongPressed:(FriendButton *)button {

NSLog(@"Delegate method!");

}


and it controller conforms to protocol. The long press gesture works but the delegate method is not being called. I'm not sure why it's not working. Is it because I have to set each buttons delegate to the UITableViewController? If so how would I do that? The buttons are set up in the interface builder.

Answer

Define your UIButton property this way

@interface FriendButton : UIButton
@property (nonatomic, weak) IBOutlet id<LongPressedButtonDelegate > delegate;
@end

Then go to Interface Builder and right click on UIButton and you will see delegate link this delegate to UITableViewController. It should work