在 touchesBegan:
CGPoint touch_point = [[touches anyObject] locationInView:self.view];
Run Code Online (Sandbox Code Playgroud)
有几十个UIImageView,存储在一个NSMutableArray images.我想知道是否有一个内置函数来检查CGPoint(touch_point)是否在其中一个图像中,例如:
for (UIImageView *image in images) {
// how to test if touch_point is tapped on a image?
}
Run Code Online (Sandbox Code Playgroud)
谢谢
跟进:
由于未知原因,pointInside永远不会返回true.这是完整的代码.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
touch_point = [touch locationInView:self.view];
for (UIImageView *image in piece_images) {
if ([image pointInside:touch_point withEvent:event]) {
image.hidden = YES;
} else {
image.hidden = NO;
}
NSLog(@"image %.0f %.0f touch %.0f %.0f", image.center.x, image.center.y, touch_point.x, touch_point.y);
}
}
Run Code Online (Sandbox Code Playgroud)
虽然我可以看到两点在NSLog输出中有时是相同的.
我也尝试过:
if ([image pointInside:touch_point withEvent:nil])
Run Code Online (Sandbox Code Playgroud)
结果是一样的.永远不会回归真实.
消除任何与图像一起使用的机会.我尝试了以下方法:
if (YES or [image pointInside:touch_point withEvent:event])
Run Code Online (Sandbox Code Playgroud)
首次点击屏幕后隐藏所有图像.
编辑2:
真的很奇怪.即使我硬编码:
point.x = image.center.x;
point.y = image.center.y;
Run Code Online (Sandbox Code Playgroud)
代码变成:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint point; // = [touch locationInView:self.view];
for (UIImageView *image in piece_images) {
point.x = image.center.x;
point.y = image.center.y;
if ([image pointInside:point withEvent:event]) {
image.hidden = YES;
NSLog(@"YES");
} else {
image.hidden = NO;
NSLog(@"NO");
}
NSLog(@"image %.0f %.0f touch %.0f %.0f", image.center.x, image.center.y, point.x, point.y);
}
}
Run Code Online (Sandbox Code Playgroud)
pointInside总是回来false......
Emi*_*mil 12
听起来像问题是你需要将坐标从视图的坐标转换为UIImageView坐标.您可以使用UIView的convertPoint方法.
尝试更换
if ([image pointInside:touch_point withEvent:event]) {
Run Code Online (Sandbox Code Playgroud)
同
if ([image pointInside: [self.view convertPoint:touch_point toView: image] withEvent:event]) {
Run Code Online (Sandbox Code Playgroud)
(请注意,您可以通过nil而不是event.)
我想这对提问者来说有点晚了,但我希望它对某人有用.
| 归档时间: |
|
| 查看次数: |
8955 次 |
| 最近记录: |