【问题标题】:UITableViewCell UITapGestureRecognizer not respondingUITableViewCell UITapGestureRecognizer 没有响应
【发布时间】:2021-02-23 12:57:19
【问题描述】:

我是 Objective-C 的初学者,我正在研究现有的代码库。

在下面的代码中,UITapGestureRecognizer 似乎没有触发 tap 方法。我已经尝试添加

[self setUserInteractionEnabled:YES];

谁能帮我弄清楚这里有什么问题。

这是我的 UITableViewCell 实现类:

@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

【问题讨论】:

    标签: objective-c uitableview uitapgesturerecognizer


    【解决方案1】:

    最可能的问题是您将视图添加到单元格本身——它们应该添加到单元格的contentView

    变化:

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

    到:

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

    除此之外,这看起来非常糟糕!

    • 您应该使用自动布局而不是设置框架
    • layoutSubviews 可以多次调用...您应该在创建视图时添加UITapGestureRecognizer,而不是每次调用layoutSubviews 时都删除/重新添加。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多