views:

502

answers:

3

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

A: 

You could certainly find the 'view' that is currently being touch event is dragging over even if it is a button. You could also use the 'touch drag enter' connection for buttons in the Interface Builder. Look at the connections tab by pressing cmd+2 when having selected a button.

willcodejavaforfood
A: 

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

Jonathan
heey.. thx for your answer but i got this warning "request for member `view`in something not a structure or union" by the line UITouch *touch = [[event....!i changed this line in UITouch *touch = [[event allTouches] anyObject]; and it work. But.. =) if i press my button it should sound a note. But now i cant press, only slide. And if i slide in my Button the note sounds more than once.. can you help me? thank you for your answer. i saw it only now. Thx
Please see my updated post.
Jonathan
A: 

This is crazy, is this really the only way to do this? If I want to have a piano keyboard with 40 keys I have to write 40 conditional statements to check the touch position?

It seems like touch drag enter and touch drag exit should do this, but they only work for the responder that records the initial touch. This seems like such a common need, I can't believe that this functionality isn't built in.

Thomas McGee