我有一组图像,想知道我触摸了哪些图像。我怎么能实现那个......? 更准确地说: “Home-Class”将实例化几个图像类:
Image *myImageView = [[Image alloc] initWithImage:myImage];
图像类看起来像这样:
- (id) initWithImage: (UIImage *) anImage
{
if ((self = [super initWithImage:anImage]))
{
self.userInteractionEnabled = YES;
}
return self;
}
稍后,我也在图像类中使用了这些触摸事件方法:
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{}
我目前的问题:无论我触摸屏幕的哪个位置,touchesBegan/Ended 方法都会被触发,但我想找出哪些图像被触摸了......
最佳答案
无论何时触摸,您都会检查该触摸是否发生在您的图像区域之间。这是示例代码,假设您有一个名为 img 的 UIImage 对象。
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:self.view];
if (location.x >= img.x && location.x <= img.x && location.y >= img.y && location.y <= img.y) {
// your code here...
}
}
关于objective-c 触摸事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3952744/