presenting ViewController with NavigationViewController swift

后端 未结 5 1726
小鲜肉
小鲜肉 2020-12-02 07:02

I have system \"NavigationViewController -> MyViewController\", and I programmatically want to present MyViewController inside a third view controller. The problem is that I

5条回答
  •  情话喂你
    2020-12-02 08:00

    I used an extension to UIViewController and a struct to make sure that my current view is presented from the favourites

    1.Struct for a global Bool

    struct PresentedFromFavourites {
    static var comingFromFav = false}
    

    2.UIVeiwController extension: presented modally as in the second option by "stefandouganhyde - Option 2 " and solving the back

    extension UIViewController {
    func returnToFavourites()
    {
        // you return to the storyboard wanted by changing the name
        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
        let mainNavigationController = storyBoard.instantiateViewController(withIdentifier: "HomeNav") as! UINavigationController
        // Set animated to false
        let favViewController = storyBoard.instantiateViewController(withIdentifier: "Favourites")
        self.present(mainNavigationController, animated: false, completion: {
            mainNavigationController.pushViewController(favViewController, animated: false)
        })
    
    }
    // call this function in viewDidLoad()
    // 
    func addBackToFavouritesButton()
    {
        if PresentedFromFavourites.comingFromFav
        {
            //Create a button
            // I found this good for most size classes
            let buttonHeight = (self.navigationController?.navigationBar.frame.size.height)! - 15
            let rect = CGRect(x: 2, y: 8, width: buttonHeight, height: buttonHeight)
            let aButton = UIButton(frame: rect)
            // Down a back arrow image from icon8 for free and add it to your image assets  
            aButton.setImage(#imageLiteral(resourceName: "backArrow"), for: .normal)
            aButton.backgroundColor = UIColor.clear
            aButton.addTarget(self, action:#selector(self.returnToFavourites), for: .touchUpInside)
            self.navigationController?.navigationBar.addSubview(aButton)
            PresentedFromFavourites.comingFromFav = false
        }
    
    }}
    

提交回复
热议问题