gar*_*hdn 1 objective-c touch ios
我希望有更好的方法来实现以下目标.我正在创建一个拼图类型的应用程序,这是我正在使用的当前代码:
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
//location of current touch
CGPoint location = [touch locationInView:self.view];
if ([touch view] == img1) {
[self animateFirstTouch:img1 withLocation:location];
} else if ([touch view] == img2) {
[self animateFirstTouch:img2 withLocation:location];
} else if ([touch view] == img3) {
[self animateFirstTouch:img3 withLocation:location];
} else if ([touch view] == img4) {
[self animateFirstTouch:img4 withLocation:location];
} else if {
......
......
} else if ([touch view] == img40) {
[self animateFirstTouch:img40 withLocation:location];
return;
}
}
Run Code Online (Sandbox Code Playgroud)
我希望有更好,更有效的方法来做到这一点,而不是命名每个图像.我想的是,如果触摸视图等于UIImageView,那么执行一些任务.touchesEnded也一样:
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
//location of current touch
CGPoint location = [touch locationInView:self.view];
if ([touch view] == image1) {
[self animateReleaseTouch:image1 withLocation:location];
} else if ([touch view] == image2) {
[self animateReleaseTouch:image2 withLocation:location];
} else if ([touch view] == image3) {
[self animateReleaseTouch:image3 withLocation:location];
} else if ([touch view] == image4) {
[self animateReleaseTouch:image4 withLocation:location];
} else if{
......
......
} else if ([touch view] == image40) {
[self animateReleaseTouch:image40 withLocation:location];
}
return;
}
Run Code Online (Sandbox Code Playgroud)
有什么帮助吗?
等等,以便您进行测试以查看它[touch view]是否等于特定视图,以便您可以将该特定视图传递给其他方法?如果是这样,它是什么视图并不重要,只关注它触及的是什么.
所以不是这样的:
if ([touch view] == image1) {
[self animateReleaseTouch:image1 withLocation:location];
} else if ([touch view] == image2) {
[self animateReleaseTouch:image2 withLocation:location];
} else if ([touch view] == image3) {
[self animateReleaseTouch:image3 withLocation:location];
}
Run Code Online (Sandbox Code Playgroud)
你应该只需要这个:
[self animateReleaseTouch:[touch view] withLocation:location];
Run Code Online (Sandbox Code Playgroud)
或者,如果您希望确保只对图片视图执行此操作,请将它们粘贴在一个数组中,并确保该视图包含在该数组中.
// do this during setup somewhere
NSArray *imageViews = [NSArray arrayWithObjects:image1, image2, ..., nil];
// do this on touch
UIView *touchedView = [touch view];
if ([imageViews indexOfObject:touchedView] != NSNotFound) {
// not not found means found!
[self animateReleaseTouch:touchedView withLocation:location];
}
Run Code Online (Sandbox Code Playgroud)
99.99%的时间你有大量的顺序命名变量,你做错了.你真正想要的是一个数组.