swift - Self.revealViewController() 返回 nil

标签 swift swrevealviewcontroller

我目前正在尝试使用平移手势来显示 Controller 。截至目前,我的打开按钮可以使用,但是当我添加最后一行时,我的程序崩溃了,因为 revealViewController 为 nil。 pods 链接: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());
    }
}

最佳答案

您可能还没有将 SWRevealViewController 设置为 rootViewController。请记住在您的Identity inspector 中将Custom ClassStoryboard 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...
}

关于swift - Self.revealViewController() 返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45045115/

相关文章:

ios - SWRevealViewController 在滑动时关闭键盘

Swift SWRevealController 子菜单

swift - 通过数字范围随机化

ios - 在 Swift 3 上运行后台线程

core-audio - swift 和 bool

ios - 方法被调用,但未正确执行

ios - SWRevealViewController插入对象:atIndex object cannot be nil

git - 从 Bitbucket 中提取 Storyboard 时出现问题

swift - SpriteKit Swift 使整个场景变暗,然后再改回来