问题描述
我是 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
解决方法
最可能的问题是您将视图添加到单元格本身——它们应该添加到单元格的 contentView
。
变化:
for (AssetView * view in self.rowViews) {
[self addSubview:view];
}
到:
for (AssetView * view in self.rowViews) {
[self.contentView addSubview:view];
}
除此之外,这看起来非常糟糕!
- 您应该使用自动布局而不是设置框架
-
layoutSubviews
可以多次调用...您应该在创建视图时添加UITapGestureRecognizer
,而不是在每次调用layoutSubviews
时删除/重新添加。立>