views:

1164

answers:

1

My subclass of UIView handles touch events and updates internal values as touches begin and as tracking occurs.

My view controller loads this custom view on screen. What's the best way to set up my view controller to listen for the value changes of my custom control?

+6  A: 

You can:

  1. Implement delegate methods in your controller and call them from your view, or
  2. Subclass UIControl instead and send UIControlEvents to your controller

when the values change (or rather when the user interacts with your control).

If your view is used to get some form of input from the user, then subclassing UIControl is a better approach.

From the iPhone Reference Library:

UIControl is the base class for controls: objects such as buttons and sliders that are used to convey user intent to the application.

So the most important distinction between UIView and UIControl is whether user intent is conveyed or not. UIView is meant to display information, while UIControl is meant to collect user input.

UPDATE:

If you decide to go with the delegate pattern, here's how your code might look like:

In your custom view's interface, define delegate like this:

@interface MyView : UIView {
    id delegate;
}
@property (assign) id delegate;
@end

and @synthesize it in the implementation.

In your view controller, set the controller to be the delegate:

MyView myView = [[MyView alloc] init];
[myView setDelegate:self];

Then, whenever the user interacts with the view (for example in touchesBegan), possibly changing the values, do this in the view:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // Possibly change the values
    if([delegate respondsToSelector:@selector(valuesChanged)]) {
        [delegate valuesChanged];
    }
}

You might also want to take a look at Delegates and Data Sources in the Cocoa Fundamentals Guide.

Can Berk Güder
I want to track point location and update an internal float when tracking occurs, but I can't figure out how to pass this float out to my view controller. If I was going to use delegation, could you explain how the syntax would look. The docs are a little confusing on this, to me.
Joe Ricioppo
Awesome! Thanks so much. I did check out the docs, but couldn't find a clear example of setting up a custom delegate. This was very helpful as it turned out to be quite simple.If I was trying to subclass UIControl instead, would I hook to it with this method? addTarget:action:forControlEvents:
Joe Ricioppo