使用xib将Gesture添加到UICollectionViewCell子视图

时间:2014-02-16 12:05:12

标签: ios iphone objective-c xib uicollectionviewcell

我正在尝试使用xib向UICollectionViewCell制作的子视图添加手势,我这样做:

·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");
    }
}

我创建了与xib文件连接的UICollectionViewCell子类,我在其中创建了容器按钮视图,如果我尝试在initialize方法中添加手势,则containerButton为nil,因此不起作用,但在prepareForReuse方法不为空,我可以在那里添加手势吗?或者我可以在其他地方做到这一点?

1 个答案:

答案 0 :(得分:1)

试试这个:

- (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];
    }
}