iphone – How do you build a custom control in UIKIt? – Education Career Blog

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?

,

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.

Leave a Comment