简体   繁体   中英

Add Gesture to UICollectionViewCell subview with xib

I'm trying to add a gesture to a subview of a UICollectionViewCell make with xib, I'm doing this:

.h

@interface MyCell : UICollectionViewCell <UIGestureRecognizerDelegate> 

@property (weak, nonatomic) IBOutlet UIView *containerButton;

@end

.m

@implementation MyCell

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self initialize];
    }
    return self;
}

- (void)initialize
{
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
    [panGestureRecognizer setDelegate:self];

    if (self.containerButton) {
        NSLog(@"ok"); //not enter here
        [self.containerButton addGestureRecognizer:panGestureRecognizer];
    }
}

-(void)prepareForReuse {
    [super prepareForReuse];
    if (self.containerButton) {
        NSLog(@"ok 2");
    }
}

I have created the UICollectionViewCell subclass connected with the xib file, where I have created the container button view, if I try to add the gesture in the initialize method, the containerButton is nil, so doesn't work, but in the prepareForReuse method is not empty, I can add the gesture there? or I can do it in other place?

Try this:

- (void)awakeFromNib
{
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
    [panGestureRecognizer setDelegate:self];

    if (self.containerButton) {
        NSLog(@"ok"); //not enter here
        [self.containerButton addGestureRecognizer:panGestureRecognizer];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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