简体   繁体   中英

UITouch with custom UIView doesn't work

I'm working on a new game, where you will drag picture around.

I've created my own custom UIView, UIPuzzle in which I used UIImageView and some value. Then I created new class called UIPuzzleView in which I created table of UIPuzzle ( UIPuzzle tab[16]; )

I added it on a main view and works fine (I tried to animate all of them). But then I want to use -(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; to check which UIPuzzle was clicked.

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

    UITouch* touch = [touches anyObject];

    int i = [self getTouchedView:[touch view]]; // this function returns me what UIPuzzle was clicked

    if(i != NAN){
        NSLog(@"%i", i);
    }
}


-(int) getTouchedView:(UIView*)touch{
    for(int i = 0 ; i < 4*4 ; i ++)
        if(touch == gread[i])
            return i;

    return NAN;
}

Here is function which adds UIPuzzle on view

-(void)initGread{

    int value = 0;
    for(int i = 0 ; i < 4 ; i ++){
        for(int j = 0 ; j < 4 ; j ++, value ++){
            // setting size and pozition of single UIPuzzle
            gread[value] = [[UIPuzzle alloc] initWithFrame:CGRectMake(j*70 + 70, i*70 + 70, 120, 120)];
            // setting picture and value to UIPuzzle
            [gread[value] setValue:value picture:[UIImage imageNamed:@"549823.jpg"]];
            // adding UIPuzzle to View
            [self addSubview:gread[value]];                                                                  
        }
    }
}

This should work, but it doesn't. It returns some random number but just on gread[0] , gread[1] , gread[4] , gread[5] .

I don't understand why it is not working. But instead of calling getTouchedView,
you can use below code

if([[touch view] isKindOfClass:[UIPuzzle class])
  return (  (UIPuzzle*)[touch view]  ).value; //because you are already setting value right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM