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];
}
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];
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.
我认为使MyViewController是childViewController(实现一个容器视图控制器)在传递视图和事件的行为方面更具可预测性。
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.