PDA

View Full Version : Delegation vs Subclassing




North Bronson
Feb 20, 2009, 10:30 AM
I've been working with Cocoa and Appkit (and UIKit) for a short time now and I'm still trying to get my head around delegation.

I have a Custom View (myCustomView) and this view has a Scroll View (myScrollView) as a subview. I want myScrollView to respond to touch for the purpose of scrolling, but I want myCustomView to receive the touch if the user is *not* scrolling (just a tap).

I found an example on the web that works perfectly. I subclass UIScrollView and override touchesEnded: to check for Dragging.

This works, but it seems like there might be cleaner way to do it than using this subclass. I thought about just using a category to extend UIScrollView, but I might want to use a stock UIScrollView elsewhere in the app.

I thought about trying to do this with delegation. I can make myCustomView a delegate of myScrollView. Then I can have myScrollView send a message to myCustomView when a touch ended *without* dragging. I don't really know how to go about doing this and was wondering if anyone had any ideas.

I see a method called scrollViewDidEndDragging:willDecelerate: and I think that might do the trick. I guess what I'm really looking for is a method like: scrollViewDidEndTouchWithoutDragging: but I don't see something like that already. Maybe I should just write that myself and add it as a category.

Also, does everyone here find themselves using delegates more often that subclassing (at least in a case like this, where the only reason I am subclassing is for one method)? It seems like subclassing is a little more "straight-forward" but it seems like delegation is stylish and "cleaner" -- if that makes sense.



narut
Feb 23, 2009, 09:29 AM
To detect a "tap" you could simply do something like this.

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

NSSet *allTouches = [event allTouches];
switch ([allTouches count]) {
case 1: {// One finger touth
UITouch *touch = [[allTouches allObjects] objectAtIndex:0];
if ([touch tapCount] == 1) { // Single tap
// Do something
}
}
}
}

The switch part is not necessary, but might come in handy if you want to extend capability to handle two-finger tap or double tap in the future. :D

If you want to use stock ScrollView then you might implement this in your View Controller class (which have this ScrollView in it's view) instead.