Reputation: 98
I am trying to add a UIView
to a view controller, but through an object of another class whose objects are currently present on the view controller in question.
myViewController is on screen -> It has objects of myNodeView added to it. I click on myNodeView and call a method in myViewController class to add a view to it.
I instantiate using myVc = [[myViewController alloc]init];
and then call the method. Is this the problem, that this is a new instance and that's why it does not add to the view currently visible. Please help me out.
Code -
// in nodeView
-(void)loadMap{
if(myVc==nil){
myVc=[[MyViewController alloc]init];
}
[myVc loadMapView];
}
// in MyViewController
-(void)loadMapView
{
if(mapView==nil)
{
self.mapView = [[MapView alloc]initWithFrame:CGRectMake(0, 0, 400, 400)];
self.mapView.backgroundColor=[UIColor whiteColor];
}
[self.view addSubview:self.mapView];
}
Upvotes: 0
Views: 722
Reputation: 11
I think make MyViewController is childViewController (Implementing a Container View Controller) is more predictable in behavior of views and events passed.
Upvotes: 0
Reputation: 2267
You are creating a new instance of MyViewController each time you call loadMap method. You can do something like this:
// Getting current viewcontroller
UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (topController.presentedViewController)
topController = topController.presentedViewController;
// Call the method
MyViewController *myVc = (MyViewController *)topController;
[myVc loadMapView];
Upvotes: 1
Reputation: 725
In MyViewcontroller, when you create the nodeView, you should be assigning the nodeView's myVc property, like this nodeView.myVc = self.
You should also make sure that nodeView's myVc property is assign.
You also don't need to check if myVc == nil in the nodeView.
Upvotes: 0