How can I call presentViewController in UIView class?

守給你的承諾、 提交于 2019-12-05 21:44:06

Call this function on your button

func infoClick()  {

        let storyboard: UIStoryboard = UIStoryboard (name: "Main", bundle: nil)
        let vc: CampainDetailView = storyboard.instantiateViewControllerWithIdentifier("campainDetailView") as! CampainDetailView
        let currentController = self.getCurrentViewController()
        currentController?.presentViewController(vc, animated: false, completion: nil)

    }

This function will create root view controller

func getCurrentViewController() -> UIViewController? {

    if let rootController = UIApplication.sharedApplication().keyWindow?.rootViewController {
        var currentController: UIViewController! = rootController
        while( currentController.presentedViewController != nil ) {
            currentController = currentController.presentedViewController
        }
        return currentController
    }
    return nil

}

This above code must work, it is working for me in Swift 2.1

You can use delegate. Add this to the Tab class

protocol TabDelegate {

    func didButtonTapped()
}

var delegate: TabDelegate?

@IBAction func btn1(sender: UIButton) {
    delegate?.didButtonTapped()
}

In the viewController where use the Tab. Set the delegate like this

let tab = Tab()
tab.delegate = self

Then push the new viewController in the delegate method And you can make a BaseViewController to do this, then all the viewController subClass it can have the same feature.

class BaseViewController: UIViewController, TabDelegate {

    func didButtonTapped() {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewControllerWithIdentifier("6")
        self.presentViewController(vc, animated: true, completion: nil)
    }
}

Class ViewControllerA: BaseViewController {
}

Class ViewControllerB: BaseViewController {
}

Add a property to this class, then your can use the methods of controller.

weak var controller:UIViewController!

self.controller?.presentViewController(vc, animated: true, completion: nil)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!