我正在使用带有 PagingEnabled 的 UIScrollView,在 UIScrollView 中我添加了三个 UIImage。它工作正常。
我想知道如何检测用户是否在 UIImage 中的两个正方形之间点击,例如:在附加的图像中,我如何检测用户是否在正方形 1 和 2 之间点击,或者用户是否在正方形 2 和 3 之间点击?
有任何想法吗?
谢谢。
我正在使用带有 PagingEnabled 的 UIScrollView,在 UIScrollView 中我添加了三个 UIImage。它工作正常。
我想知道如何检测用户是否在 UIImage 中的两个正方形之间点击,例如:在附加的图像中,我如何检测用户是否在正方形 1 和 2 之间点击,或者用户是否在正方形 2 和 3 之间点击?
有任何想法吗?
谢谢。
将手势添加到图像视图
imageView.userInteractionEnabled = YES;
UIPinchGestureRecognizer *pgr = [[UIPinchGestureRecognizer alloc]
initWithTarget:self action:@selector(handlePinch:)];
pgr.delegate = self;
[imageView addGestureRecognizer:pgr];
[pgr release];
:
:
- (void)handlePinch:(UIPinchGestureRecognizer *)pinchGestureRecognizer
{
//handle pinch...
}
为了检测单个或多个水龙头使用UITapGestureRecognizer
,它是UIGestureRecognizer
. 您不应忘记将该userInteractionEnabled
属性设置为YES
,因为UIImageView
-class 将默认值更改为NO
。
self.imageView.userInteractionEnabled = YES;
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap:)];
// Set the number of taps, if needed
[tapRecognizer setNumberOfTouchesRequired:1];
// and add the recognizer to our imageView
[imageView addGestureRecognizer:tapRecognizer];
- (void)handleTap:(UITapGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateEnded) {
// if you want to know, if user tapped between two objects
// you need to get the coordinates of the tap
CGPoint point = [sender locationInView:self.imageView];
// use the point
NSLog(@"Tap detected, point: x = %f y = %f", point.x, point.y );
// then you can do something like
// assuming first square's coordinates: x: 20.f y: 20.f width = 10.f height: 10.f
// Construct the frames manually
CGRect firstSquareRect = CGRectMake(20.f, 20.f, 10.f, 10.f);
CGRect secondSquareRect = CGRectMake(60.f, 10.f, 10.f, 10.f);
if(CGRectContainsPoint(firstSquareRect, point) == NO &&
CGRectContainsPoint(secondSquareRect, point) == NO &&
point.y < (firstSquareRect.origin.y + firstSquareRect.size.height) /* the tap-position is above the second square */ ) {
// User tapped between the two objects
}
}
}