Retrieving values from subviews Objective-c
I have created a subclass of a UIView which is a rotating wheel. This wheel is part of another UIView which has an image in the top right corner. When the wheel is turned, in the touchMoved function the right most item is returned (its number). I need to then change the parent's image automatically when the subview is turned (when th开发者_如何学Ce number is returned)
Assuming I have this number in the subview, how may I return this to the parent, or change the image (in the parent UIView) from the subview?
Thanks
First, create a protocol which defines the method(s) you want to call in your superview:
@protocol wheelViewDelegate {
-(void)doSomething;
}
Your superview needs to implement this protocol:
@interface superView:UIView<wheelViewDelegate> {
...
}
...
@end
Also, you obviously need to implement the doSomething
method.
The UIView, which contains the wheel needs to be a subclass of UIView and hold the delegate, like this:
@interface WheelView : UIView {
id<wheelViewDelegate> delegate;
...
}
@propery (nonatomic, assign) id<wheelViewDelegate> delegate;
...
@end
Don't forget to @synthesize id;
in your implementation.
Now, you can call the doSomething
in your superview from the subview:
[self.delegate doSomething];
EDIT:
Okay, I thought this was obvious, but, of course, you need to set the delegate like this:
//In your superView:
WheelView* wv = [WheelView initSomeHow];
wv.delegate = self;
The delegate method mentioned by Phlibbo is one way to do this. Since your custom view subclass is more like a control with a value, I would subclass UIControl
instead of UIView
and use the UIControlEventValueChanged
event.
In your custom subclass notify the value has changed (maybe in your touchedEnded:withEvent:
):
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[self sendActionsForControlEvents:UIControlEventValueChanged];
}
Now observe value changes in your controller, and let the controller update the image in the other view.
- (void) viewDidLoad {
[wheelControl addTarget:self action:@selector(wheelValueChanged:) forControlEvents:UIControlEventValueChanged];
}
- (void) wheelValueChanged:(id)sender {
// update your image based on the wheel value of sender (wheelControl in this case).
}
精彩评论