Search code examples
iphoneobjective-ctouches

how to call image on touch event in iphone


i have created an application in which there are 2 imageviews and i have added image on image view.i wnt that when i click on my image the image should get selected and the value should be saved in sqlite database.So for that i have created touches method,and added flags for both the images so when particular image is selected it is identified by its flag. this is my code:

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

    UITouch *touch = [[event allTouches] anyObject];

    CGPoint location= [touch locationInView:self.view];

    if(CGRectContainsPoint(firstImage.frame, location)) 
    {
        //set some flag like
        select=1;        
    }
    else if(CGRectContainsPoint(secImage.frame, location))
    {
        select=2;        
    }
    [mComment resignFirstResponder];

}         

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

    UITouch  *touch = [[event allTouches] anyObject]; 
    CGPoint location = [touch locationInView:self.view];


    if(CGRectContainsPoint(firstImage.frame, location)) {   
        if(select==1) {

            var=1;
        }
         else if(CGRectContainsPoint(secImage.frame, location))  { 

            if(select==2) {
                vars=2;
            }
            select=0; 
        }
    }
}

But i am having a problem,when i select my first image it properly gets into the if part and stores value 1 into var 1 but when i click secimage it does not enter into elseif part,it just comes out of the loop.What may be the problem .Please help me in solving this problem.thanks


Solution

  • The following change should fix the problem:

    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 
    
        UITouch  *touch = [[event allTouches] anyObject]; 
        CGPoint location = [touch locationInView:self.view];
    
    
        if(CGRectContainsPoint(firstImage.frame, location)) {   
            if(select==1) {
    
                var=1;
            }}
        if(CGRectContainsPoint(secImage.frame, location))  { 
    
            if(select==2) {
                vars=2;
            }}
        select=0; 
    }
    

    Your above code wasn't working because if(CGRectContainsPoint(firstImage.frame, location) == YES, it will never reach the line if(CGRectContainsPoint(secImage.frame, location)

    The code could also be cleaned up a bit. Not sure this is the ideal way of implementing these two methods, but it could work anyway.