简体   繁体   English

使用Xib将手势添加到UICollectionViewCell子视图

[英]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: 我试图将手势添加到带有xib的UICollectionViewCell的子视图中,我正在这样做:

.h 。H

@interface MyCell : UICollectionViewCell <UIGestureRecognizerDelegate> 

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

@end

.m .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? 我创建了与xib文件连接的UICollectionViewCell子类,在其中创建了容器按钮视图,如果我尝试在initialize方法中添加手势,containerButton为nil,因此无效,但是在prepareForReuse方法中是不为空,我可以在其中添加手势吗? 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];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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