Self.revealViewController()返回nil

时间:2017-07-11 21:56:52

标签: swift swrevealviewcontroller

我目前正试图通过平移手势来显示控制器。截至目前,我的打开按钮工作,但是当我添加最后一行时,我的程序崩溃,因为revealViewController是零。链接到pod:https://github.com/John-Lluch/SWRevealViewController

    import Foundation
    import UIKit
    class MainViewController : UIViewController{
    @IBOutlet weak var mainButton: UIView!
    @IBOutlet weak var Open: UIBarButtonItem!
    override func viewDidLoad() {
        super.viewDidLoad()

    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated);
        mainButton.makeCircle();
        Open.target = self.revealViewController()
        Open.action = #selector(SWRevealViewController.revealToggle(_:));
        self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer());
    }
}

2 个答案:

答案 0 :(得分:2)

您可能无法将SWRevealViewController设置为rootViewController。请务必在身份检查器中将自定义类 Storyboard ID 设置为SWRevealViewController

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let rootVC = storyboard.instantiateViewController(withIdentifier: "SWRevealViewController")    
    self.view.window?.rootViewController = rootVC

    // Cont. with your code...
}

如果您需要在开头显示登录页面,则需要AppDelegate中的某个功能,该功能允许窗口更新rootViewController

func changeRootVCToSWRevealVC () {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let rootVC = storyboard.instantiateViewController(withIdentifier: "SWRevealViewController")
    if let window = self.window{
        window.rootViewController = rootVC
    }
}

用户登录后,您可以将rooViewController更改为SWRevealViewController

if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
    appDelegate.changeRootVCToSWRevealVC()
}

如果您有一个变量存储上次登录的状态,并希望直接导航到导航抽屉菜单而不是LoginViewController

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    let rootVCId = isLoggedin ? "SWRevealViewController" : "LoginViewController"
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let rootVC = storyboard.instantiateViewController(withIdentifier: rootVCId)    
    self.view.window?.rootViewController = rootVC

    // Cont. with your code...
}

答案 1 :(得分:0)

我刚刚遇到同样的问题,并发现了这篇文章。我的问题更像是一个" oops!"因为我错过了一些显而易见的东西,花了30分钟时间抓住它。 :facepalm:

如果接受的答案对您不起作用,请检查以确保您已通过插座将菜单属性连接到故事板。

夫特:

@IBOutlet weak var menuButton:UIBarButtonItem!

override func viewDidLoad() {
    if (self.revealViewController() != nil) {
        menuButton.target = self.revealViewController()
        menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
    }
}