简体   繁体   中英

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 the 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).
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM