简体   繁体   中英

Navigate from UIView to UIViewController without storyboard and navigation controller

Is there a way to navigate from a UIView , which is part of a UIViewController , to another UIViewController neither using storyboards nor navigation controllers?

I have a UITapGestureRecognizer which I want to navigate to another UIViewController ( BuyController() ) whenever it is tapped once. Accordingly, my code looks like this:

//handle singleTap
func singleTapOnLikesDetected(_ sender: UITapGestureRecognizer) {

    print("check") //works
    let toController = BuyController()
    BarController().pushViewController(toController, animated: true) //error occurs since BarController is no navigationcontroller

}

BarController ( UITabBarController , UITabBarControllerDelegate ) is my rootViewController in the AppDelegate.swift . The UIView however belongs to another UIViewController called HomeController ( UIViewController , UIScrollViewDelegate ). I do not use storyboards at all and I would like to keep it that way, as I am going to work on a project in a team (thus, a programmatic solution would be very welcome)...

You can simply do this to navigate, without using navigationController :

self.present(toController, animated: true, completion: nil)

Or Use this,

UIApplication.shared.keyWindow?.rootViewController?.present(toController, animated: true, completion: nil)

Only UIViewControllers can present other UIViewControllers not UIViews so your won't find the present method on the UIView. You also can't replace self with HomeController() because that creates a new HomeController with it's own UIView which hasn't been added to any other view (as the error suggests).

You have a couple of options really:

1) Create a protocol/delegate on your UIView and make the HomeController conform to it. Then the UIView can call the method in the protocol and the HomeController do the actual switching.

2) You could get the root view controller to present the new UIViewController like this: UIApplication.shared.keyWindow?.rootViewController?.present(viewController, animated: true, completion: nil)

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