0

首先,我只想说我是从Objective-C开始的。

这是我的项目的布局: mainView > ScrollView inside mainView > ImageView inside ScrollView

mainView 和 scrollView 都是在 Storyboard 中创建的。所有的 imageView 都是以编程方式创建的,并作为 scrollView 中的子视图。

我只有一个名为 ViewController 的类。

这是我的问题:如何在我的 scrollView 内处理 ImageView 上的单点触摸?让我知道是否有不清楚的地方。

更新:

NSString *imagePath = [NSString stringWithFormat:@"%@/%@ (%i).png", path, path, nbrImage];
            CGRect myImageRect = CGRectMake(40, 25 + (line*lenght), 75, 75);
            self.img = [[UIImageView alloc] initWithFrame:myImageRect];
            [self.img setImage:[UIImage imageNamed:imagePath]];

            UITapGestureRecognizer* singleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
            singleTapGestureRecognizer.numberOfTapsRequired = 1;
            singleTapGestureRecognizer.numberOfTouchesRequired = 1;     
            singleTapGestureRecognizer.cancelsTouchesInView = NO;
            [self.img addGestureRecognizer:singleTapGestureRecognizer];

            [self.scrollView addSubview:self.img];

- (void)handleSingleTapFrom:(UITapGestureRecognizer*)recognizer {

   UIImageView* imageView = (id)recognizer.view;
   NSLog(@"Test");
}

编辑:这行得通,在@selector中我写了handleSingleTap而不是handleSingleTapFrom:

4

2 回答 2

1

您可以将 UIControl 添加到您的 imageView 以执行您想要的任何选择器以响应单次触摸。只需将背景颜色设置为清除,将框架设置为 imageView.frame,将控件添加为 imageView 的子视图并说

[myControl addtarget:self action:@selector(whateverYouWantToDo) forControlEvents:UIConntrolEventTouchUpInside];

编辑:

UIControl *myControl = [[UIControl alloc] initWithFrame:imageView.frame]; 
[myControl setBackgroundColor:[UIColor clearColor]]; 
[myControl addTarget:self action:@selector(doWork) forControlEvents:UIControlEventTouchUpInside]; 
[imageView addSubview:myControl]; 

然后只需实现 doWork 方法来做任何你想做的事情。我可能误解了您的问题,但如果您想在用户触摸滚动视图中的图像时执行操作,这就是我所做的方式。

于 2012-05-09T19:08:20.703 回答
1

使用UITapGestureRecognizer. 例如,

    UITapGestureRecognizer* singleTapGestureRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)] autorelease];
    singleTapGestureRecognizer.numberOfTapsRequired = 1;
    singleTapGestureRecognizer.numberOfTouchesRequired = 1;     
    singleTapGestureRecognizer.cancelsTouchesInView = NO;
    [imageView addGestureRecognizer:singleTapGestureRecognizer];

使用处理程序方法:

- (void)handleSingleTapFrom:(UITapGestureRecognizer*)recognizer {

    UIImageView* imageView = (id)recognizer.view;
    ...
}
于 2012-05-09T19:11:02.400 回答