I have the following code in my app which I could just copy and paste each time, but I would rather make it so it is reusable in other areas too. It allows me to drag UIImageViews around the screen but I don’t like the fact that it is very prone to error with the slightest of typos!
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:self.view];
if (touch.view == first) {
first.center = location;
if (((first.center.x >= 100) && (first.center.y >= 100) &&
(first.center.x <= 150) && (first.center.y <= 150))) {
first.center = CGPointMake(125, 125);
[first setUserInteractionEnabled:NO];
theCentre = [[NSUserDefaults standardUserDefaults] init];
NSString *centre = NSStringFromCGPoint(first.center);
[theCentre setObject:centre forKey:@"centre"];
// NSLog(@"%@", [theCentre objectForKey:@"centre"]);
[theCentre synchronize];
}
}
if (touch.view == second) {
second.center = location;
if (((second.center.x >= 150) && (second.center.y >= 150) &&
(second.center.x <= 180) && (second.center.y <= 180))) {
second.center = CGPointMake(165, 165);
[second setUserInteractionEnabled:NO];
theCentre = [[NSUserDefaults standardUserDefaults] init];
NSString *centre = NSStringFromCGPoint(second.center);
[theCentre setObject:centre forKey:@"secondCentre"];
// NSLog(@"%@", [theCentre objectForKey:@"centre"]);
[theCentre synchronize];
}
}
if (touch.view == third) {
third.center = location;
if (((third.center.x >= 200) && (third.center.y >= 200) &&
(third.center.x <= 230) && (third.center.y <= 230))) {
third.center = CGPointMake(215, 215);
[third setUserInteractionEnabled:NO];
theCentre = [[NSUserDefaults standardUserDefaults] init];
NSString *centre = NSStringFromCGPoint(third.center);
[theCentre setObject:centre forKey:@"thirdCentre"];
// NSLog(@"%@", [theCentre objectForKey:@"centre"]);
[theCentre synchronize];
}
}
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[self touchesBegan:touches withEvent:event];
}
I have tried fast enumeration but that made one imageView move and the others just disappear off the screen! Obviously not the desired effect…
I recommend using UIGestureRecognizers for this. After you set up your image views write:
And then implement the gesture handler:
This code is untested (written in notepad), but this is the right direction.