如何在 UIView class 中调用 presentViewController?

How can I call presentViewController in UIView class?

我的项目中有一个自定义选项卡,它位于应用程序的每个屏幕上,因此我制作了自定义 UIView class 和 xib 文件并在其中添加了按钮。现在我想要我的按钮在具有不同 story board id 的不同屏幕上进行导航。但是我无法从 UIView class 调用 presentViewController。以前我在 extension class 中自定义函数以在屏幕之间导航,但 UIView class 也无法调用该函数。

import UIKit

@IBDesignable class tab: UIView {

var view: UIView!

@IBAction func btn1(sender: UIButton) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewControllerWithIdentifier("6")
    self.presentViewController(vc, animated: true, completion: nil)
}
override init(frame: CGRect) {
    super.init(frame: frame)
    xibSetup()
}

required init?(coder aDecoder: NSCoder) { 
    super.init(coder: aDecoder) 
    xibSetup()
}

func xibSetup() {
    view = loadViewFromNib() 
    view.frame = bounds 
    view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] 
    addSubview(view)
} 
func loadViewFromNib() -> UIView {
    let bundle = NSBundle(forClass: self.dynamicType)
    let nib = UINib(nibName: "tab", bundle: bundle) 
    let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
    return view
} 
}

给这个class添加一个属性,然后你就可以使用controller的方法了。

弱变量 controller:UIViewController!

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

您可以使用委托。将此添加到选项卡 class

protocol TabDelegate {

    func didButtonTapped()
}

var delegate: TabDelegate?

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

在 viewController 中使用 Tab。 像这样设置委托

let tab = Tab()
tab.delegate = self

然后在委托方法中推送新的viewController 你可以制作一个 BaseViewController 来执行此操作,然后它的所有 viewController 子类都可以具有相同的功能。

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 {
}

在你的按钮上调用这个函数

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)

    }

此函数将创建根视图控制器

 func getCurrentViewController() -> UIViewController? {

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

}

上面的代码必须有效,它在 Swift 4.0

中对我有用