PDA

View Full Version : Subclassing UIButton




neil.b
Jan 6, 2009, 05:36 PM
I've been creating my own buttons by subclassing UIButton and drawing the buttons programatically. In order to provide touch functions I've been using the addTarget:action:forControlEvent method but I've come unstuck.

Even though I can use the addTarget method to capture touch events, only the sender gets sent to the selector and so no touch information is available (locationInView etc.)

For example, creating the button;

UIButton *myButton = [[UIButton alloc] initWithFrame:CGRectMake(100,100,50,50)];
[myButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:myButton];

And the selector;

-(void) buttonPressed:(id)sender
{
....
}

As far as I can figure out, there's no way to prototype the buttonPressed selector so that you can pass it touch information in the same way that;

-(void) touchBegain:(NSSet *)touches withEvent:(UIEvent *)sender

does.

Can anyone give me some pointers?

Thanks



drivefast
Jan 6, 2009, 06:11 PM
there's a lot of control events in the same enum where UIControlEventTouchDown is. but if none of them satisfies you, why dont you give up subclassing the UIButton, and just go and subclass an UIView containing a picture of your button? it's more work because you would have to keep track of the image to display on each kind of event, but you have more granular access.

neil.b
Jan 6, 2009, 06:49 PM
Thanks.

What I'm playing around with doesn't particularly require the subclass to be of UIButton so UIView would do.

However, I'm still unsure of how to achieve the same result with a UIView.

I've got a matrix of buttons and what I want to trap is if the user presses a button then drags their finger outside of the bounds of the button, but with more accuracy than the UIControlEventTouchDragEnter/Exit events give. At that point I want to detect if the users finger has moved into the bounds of another button, therefore I need coordinates within the view.

drivefast
Jan 6, 2009, 07:30 PM
the way you describe it, sounds like you're still ok subclassing the UIButton, yet you may want to focus on using it as a UIView for what you need. did you had a chance to look at the MoveMe (http://developer.apple.com/iphone/library/samplecode/MoveMe/index.html) sample app from apple? also the Touches (http://developer.apple.com/iphone/library/samplecode/Touches/index.html#//apple_ref/doc/uid/DTS40007435) sample may help too.

neil.b
Jan 7, 2009, 03:07 AM
Somehow I've never noticed that Touches example before. That's given me some food for thought.

Thanks :)