如何在UITableViewCell中只添加一个tapGesture图像?
我有一个tableView
自定义单元格。我在一个单元中有一个imageView
。我想添加到这imageView
一个tapGesture
加载功能,然后我点击imageView
。所以我有这样的代码为cellForRowAtIndexPath:
如何在UITableViewCell中只添加一个tapGesture图像?
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected:)];
singleTap.numberOfTapsRequired = 1;
[cell.image setUserInteractionEnabled:YES];
[cell.image addGestureRecognizer:singleTap];
和
-(void)tapDetected:(id)sender{
NSLog(@"single Tap on imageview");
}
我的问题是,当我滚动这个水龙头多次添加和变更到imageView
表视图,然后先单击更改。
我怎样才能改变只添加一个时间tapGesture
所有细胞?
如果你有一个自定义单元格,你可以像这样的功能:
-(void) addTapGesture:(UITapGestureRecognizer*)tapGesture {
if (self.tapGesture == nil) {
[self.image setUserInteractionEnabled:YES];
[self.image addGestureRecognizer:singleTap];
self.tapGesture = tapGesture
}
}
这样你一定要每单元设置tapGesture只有一次
。
让我知道这是否能够解决您的问题
的问题
现在,你添加新的TapGestureRecognizer每次cellForRowAtIndexPath
被称为,这是每一个细胞是关于时间出现在屏幕上!
解决方案1:保留旧手势识别器
你也可以检查单元格已经包含了手势识别,如果它不添加一个新的。这将确保只有一个TapGestureRecognizer被施加到每个单元:
// Check if the cell already contains a gesture recognizer
// if not, add one!
if (cell.gestureRecognizers.count == 0) {
// Now add the tap gesture recognizer and it will be the only one
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected:)];
singleTap.numberOfTapsRequired = 1;
[cell.image setUserInteractionEnabled:YES];
[cell.image addGestureRecognizer:singleTap];
}
注意:您也许应该检查并确保该单元格中包含 正是你desire-你可能要添加更多的 手势识别手势识别器给你的细胞,然后你必须确定它包含正确的一个!
解决方案2:删除姿势识别
删除从单元中的所有手势识别添加TapGestureRecognizer之前。这将确保只有一个TapGestureRecognizer被施加到每个单元:刚刚您自定义单元格
// Removes all gesture recognizers in the cell
for (UIGestureRecognizer *recognizer in cell.gestureRecognizers) {
[cell removeGestureRecognizer:recognizer];
}
// Now add the tap gesture recognizer and it will be the only one
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected:)];
singleTap.numberOfTapsRequired = 1;
[cell.image setUserInteractionEnabled:YES];
[cell.image addGestureRecognizer:singleTap];
,这样做:在你的cellForRowAtIndexPath(我使用SWIFT为例)
class YourCell:UITableViewCell{
//add a variable to track has added a tapgesture to image view
var isAddedTapGesture = false
......
}
:
if(cell.isAddedTapGesture == false){
//add the tap gesture to your image
cell.cell.isAddedTapGesture = true
}
在您的自定义单元头中,创建一个属性,如
@property(强,非原子)UITapGestureRecognizer * tapGesture;
为手势添加Getter方法。
- (UITapGestureRecognizer*)tapGesture{
if (!_tapGesture) {
_tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected:)];
}
return _tapGesture;
}
和awakeFomNib函数内部,取出并重新 - 添加手势对于像下面的图像视图。
[self.image removeGestureRecognizer:self.tapGesture];
[self.image addGestureRecognizer:self.tapGesture];
希望这会有帮助。
您是想要为所有图像使用相同的轻击手势,还是在图像视图已经包含轻击手势时跳过? –
我想为行中的所有图像添加相同的手势,但只有一次。我的功能是这样做的,但是当我滚动桌子时不断。我只想第一次添加,因为如果通过我的水龙头功能不断增加值的变化... – user3745888
是否有任何理由不能先删除任何现有的水龙头识别器,然后添加它? – DMan