Search code examples
iosobjective-ccocoa-touchtouch-event

How can I move multiple objects with Objective-C


Here is my code

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *myTouch = [[event allTouches] anyObject];
    UITouch *myTouch2 = [[event allTouches] anyObject];
    UITouch *myTouch3 = [[event allTouches] anyObject];

    button.center = [myTouch locationInView:self.view];
    button2.center = [myTouch2 locationInView:self.view];
    button3.center = [myTouch3 locationInView:self.view];   
}

The problem is, when I try to move one of the buttons, they all move at the same time and same position. I want to be able to move buttons separately and freely. How do I do that? Any suggestions?


Solution

  • Use the following to determine which button it is:

    UITouch *touch = [[event touchesForView:self.view] anyObject];
    
    CGPoint location = [touch locationInView:touch.view];
    
    if(CGRectContainsPoint(button.frame, location)) 
    {
        button.center = [myTouch locationInView:self.view];
    
    }
    else if(CGRectContainsPoint(button2.frame, location)) 
    {
        button2.center = [myTouch locationInView:self.view];
    
    }
    else if(CGRectContainsPoint(button3.frame, location)) 
    {
        button3.center = [myTouch locationInView:self.view];
    
    }