简体   繁体   中英

How do I add a UIView to a UIViewController from the menu tab bar controller with swift?

So, I have an app which has as its root view controller a menu bar controller class which I named MenuTabBarController , and which holds a number of UIViewControllers . One of those view controllers is the homepage which I called HomeViewController and which is displayed on app load since it occupies index 0 position. What I'm trying to do is create a subview in the viewDidLoad method of MenuTabBarController , but place this subview within HomeViewController . Here's what I came up with

    let homeViewController = HomeViewController()//An instance of HomeViewController created at global level

    class MenuTabBarController: UITabBarController,UITabBarControllerDelegate,UIPopoverPresentationControllerDelegate{

        var mainBox: UIView!//This is the sub view reference declared as an optional

        override func viewDidLoad()

            super.viewDidLoad()

            self.delegate = self


            mainBox = UIView(frame: CGRectMake(0,0,200,200))//Initialize mainBox

            homeViewController.view.addSubview(mainBox)//Attempt to add mainBox to homeViewController

        }//End viewDidLoad

    }//End class definition

Well the mainBox doesn't get added because when I attempt to run the app, a blank page stares at me. If I add the mainBox to the menu bar's view like so

    self.view.addSubview(mainBox)

it gets added. How can I add it to the homeView though?

You can also do it by accessing index of tabs by getting all controllers of tab bar controller.

(self.viewControllers[0] as! HomeViewController).view.addSubview(mainBox) 

Hope it will work for you!!!

You can't add subview to tabbar controller because it's manage all tabs, it's not visible as VC to users. So if you want to ass view in any tac(VC) then you can add it in it's viewdidload method or If you want to add view from tabbarcntoller class then you can get all view controllers in array by calling viewControllers by self . self.viewControllers[0] is you first VC (Home in your case) where self.viewControllers[1] should be second.

Hope this will help :)

It seems that you are creating an extra instance of the home view controller (that is never made visible btw.) and add the sub view into it.

I think what you really want to do is to create and add the sub view in viewDidLoad of your HomeViewController class.

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