truespan
truespan

Reputation: 189

UITableViewCell UITapGestureRecognizer not responding

I am a beginner with Objective-C and I am working on existing code base.

In the following code, UITapGestureRecognizer doesn't seem to trigger tap method. I have tried adding

[self setUserInteractionEnabled:YES];

Can anyone help me figure out what is not working here.

This is my UITableViewCell implementation class:

@interface ELCAssetCell ()

@property(nonatomic, strong) NSArray * rowAssets;
@property(nonatomic, strong) NSMutableArray * rowViews;

@end

@implementation ELCAssetCell

@synthesize rowAssets;

- (id)initWithReuseIdentifier:(NSString *)_identifier cellWidth:(CGFloat)width {

 if (self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:_identifier]) {

    self.rowViews = [[NSMutableArray alloc] init];

    for (int i = 0; i < 4; i++) {
        [self.rowViews addObject:[[AssetView alloc] initWithFrame:CGRectZero]];
    }

    for (AssetView * view in self.rowViews) {
        [self addSubview:view];
    }

    _width = width;
 }

return self;
}

- (void)layoutSubviews {

  [super layoutSubviews];
  CGFloat itemWidth = _width / 4;
  CGRect frame = CGRectMake(2, 2, itemWidth - 4, itemWidth - 4);

  for (AssetView * view in self.rowViews) {

      [view setFrame:frame];
      [[view gestureRecognizers] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL 
       *stop) {
           [view removeGestureRecognizer:obj];
          }];
      [view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self 
      action:@selector(tap:)]];

    frame.origin.x += itemWidth;
  }
 }

 - (void)tap:(UITapGestureRecognizer *)gest {

     [self.delegate assetPressed:[(AssetView *)[gest view] asset]];
     [(AssetView *)[gest view] toggleSelection];
   }


  @end

Upvotes: 0

Views: 75

Answers (1)

DonMag
DonMag

Reputation: 77462

The most likely problem is that you are adding the views to the cell itself -- they should be added to the cell's contentView.

Change:

for (AssetView * view in self.rowViews) {
    [self addSubview:view];
}

to:

for (AssetView * view in self.rowViews) {
    [self.contentView addSubview:view];
}

Aside from that, this looks absolutely terrible!

  • you should be using auto-layout instead of setting frames
  • layoutSubviews can be called multiple times... you should be adding the UITapGestureRecognizer when you create the views, not removing / re-adding every time layoutSubviews is called.

Upvotes: 2

Related Questions