TouchesMoved with Button?

前端 未结 2 625
长发绾君心
长发绾君心 2021-01-25 06:50

Is it possible to use the touchesMoved function with buttons instead of UIImageViews?

2条回答
  •  独厮守ぢ
    2021-01-25 07:07

    Yes.

    In your .h file

    IBOutlet UIButton *aButton;
    

    In your .m file

        -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
    {
        UITouch *touch = [[event touchesForView:self.view] anyObject];
    
        CGPoint location = [touch locationInView:touch.view];
    
        if(CGRectContainsPoint(p1.frame, location)) 
        {
            if (!p1.isHighlighted){
                [self pP01];
                [p1 setHighlighted:YES];
        }
    }else {
            [p1 setHighlighted:NO];
        }
        //
        if(CGRectContainsPoint(p2.frame, location)) 
        {
            if (!p2.isHighlighted){
                [self pP02];
                [p2 setHighlighted:YES];
            }
        }else {
            [p2 setHighlighted:NO];
        }
        if(CGRectContainsPoint(p3.frame, location))
        {
            if (!p3.isHighlighted){
                [self pP03];
                [p3 setHighlighted:YES];
            }
        }else {
            [p3 setHighlighted:NO];
        }
    }
    

    And finally, in Interface Builder, connect your button to 'aButton' and turn off "User Interaction Enabled" for your button. This is important because it allow touchesMoved to handle it.

    I have adjusted the code above to check the buttons highlighted state. This is to stop it from firing the button multiple times when you drag your finger inside the area.

    To get your "piano keys" to work when you tap them, use -(void)touchesBegan

    To set your button highlight states back to = NO;, use -(void)touchesEnded

    I have had to find out the exact same thing you are after. I couldn't figure out Touch Drag Enter

    So to avoid multiple posts on the subject, please check out my question and answers.

    question 1

    question 2

提交回复
热议问题