1

我有一个UITableViewwith UITableViewCellwhich 持有UIImageView的。现在我想 UILongGestureRecognizerUIImageView's 中添加一个。但这不起作用。UILongGestureRecognizer关于self.view的作品...

如何实现UILongGestureRecognizer它在UIImageView's 中的UITableViewCell's 上工作?

表视图控制器.h

@interface MagTableViewController : UITableViewController <UIGestureRecognizerDelegate>

@property (strong, nonatomic) UILongPressGestureRecognizer *longPress;
@property (strong, nonatomic) NSMutableArray *tableContent;

@end

表视图控制器.m

- (void)viewDidLoad
{
    self.longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressed:)];
    self.longPress.minimumPressDuration = 0.2;
    self.longPress.numberOfTouchesRequired = 1;
    //[self.view addGestureRecognizer:self.longPress];  // This works! 
}

// [...]

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    UIImageView *imvLeft = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
    [imvLeft setImageWithURL:[NSURL URLWithString:self.tableContent[@"url"]]];
    imvLeft.userInteractionEnabled = YES; // added soryngod's hint, but does not
    // solve the problem, as only the last row of 5 is enabled...
    [imvLeft addGestureRecognizer:self.longPress];  // does not work... 

    [cell.contentView addSubview:imvLeft];

    return cell;
}

-(void)longPressed:(UILongPressGestureRecognizer *)recognizer {
// do stuff

}
4

2 回答 2

1

您需要imvLeft.userInteractionEnabled = YES; 默认设置为NO.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressed:)];
        longPress.minimumPressDuration = 0.2;
        longPress.numberOfTouchesRequired = 1;
        imvLeft.userInteractionEnabled = YES;
        [imvLeft addGestureRecognizer:self.longPress];
        [longPress release];
    [cell.contentView addSubview:imvLeft];

    return cell;
}

如果你想识别被按下的图像视图

-(void)longPressed:(UILongPressGestureRecognizer *)recognizer 
{

 UIImageView *img = (UIImageView *)recognizer.view;

//do stuff
}
于 2013-07-16T14:05:16.457 回答
1

除了设置之外imvLeft.userInteractionEnabled = YES,您还需要为每个图像视图制作不同的手势识别器。按照设计,UIGestureRecognizer必须与单个视图相关联。您看到的症状是识别器与前一个单元格分离的结果,因为每个新单元格都调用了addGestureRecognizer:

请参阅相关问题:您可以将 UIGestureRecognizer 附加到多个视图吗?

于 2013-07-16T19:05:48.017 回答