简体   繁体   中英

ios pass data between custom view and view controller

I'm a beginner in iOS development. I have a custom view:

@interface MyView : UIView {

In the ViewController, I add this view as a subview (would be better to do in another way, maybe in the Storyboard?):

MyView *myView = [[MyView alloc]initWithFrame:myFrame];
[self.view addSubview:myView];

in it, I follow the touches on screen, and I have a touchesEnded method:

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    // myValue is a class variable of MyView
    myValue = doSomething();
}

Now, how can I get the value of myValue in the ViewController? Maybe a listener or a callback that can be invoked inside touchesEnded in MyView?

Well, a simple way is to keep a reference to the view controller in MyView , eg, define a property like:

@property (weak,nonatomic) MyViewController *viewController;

And then in the view controller assign myView.viewController = self . This way you can then call whatever methods on the view controller from MyView , eg, [viewController myView:self changedValue:myValue] or whatever.

(And, yes, it's possible to add the custom view subclass directly in the storyboard. Just add a generic UIView in the storyboard and change its class to MyView .)

There are of course many alternative ways, eg, notifications, or simply polling a property of MyView from the view controller if its only of interest at certain times, etc.

For instance, you can post a NSNotification in touchesEnded method of your view:

[[NSNotificationCenter defaultCenter] postNotificationName:@"ViewDidTouch" object:self];

Listen for this notification in your view controller. To achieve that add in the view controller's method viewDidLoad a line:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onViewDidTouch:) name:@"ViewDidTouch" object:nil];

And then implement below method in your view controller:

- (void) onViewDidTouch:(NSNotification*)notification
{
    // do something
}

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