从自定义UIViewController

时间:2019-02-12 09:23:09

标签: ios swift storyboard

我正在尝试在iOS App中实现侧面导航菜单(在Android中是一个导航菜单)。到目前为止,我尝试了以下操作:-

mystoryboard

AppDelegate.swift:-

class AppDelegate: UIResponder, UIApplicationDelegate {
 var window: UIWindow?
 var bridge: RCTBridge!

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

 let sb = UIStoryboard(name: "mystoryboard", bundle: Bundle.main)
 let rootViewController: UIViewController = 
 sb.instantiateViewController(withIdentifier: 
 "NativeLabelSwiftViewController") as UIViewController

 let navigationController = UINavigationController(rootViewController: 
 rootViewController)

 window = UIWindow(frame: UIScreen.main.bounds)
 window!.rootViewController = navigationController
 window!.makeKeyAndVisible()

 return true
}

上面是我的AppDelegate类,因为它是一个React Native项目,我们也有生成的代码。这里添加了以下代码以通过以下代码实例化我的rootViewClass(NativeLabelSwift):-

  let sb = UIStoryboard(name: "mystoryboard", bundle: Bundle.main)
  let rootViewController: UIViewController = 
   sb.instantiateViewController(withIdentifier: 
  "NativeLabelSwiftViewController") as UIViewController

NavigationLabelSwiftViewController.swift(自定义视图类):-

 class NativeLabelSwiftViewController: UIViewController{

   var bridge: RCTBridge!
   override func viewDidLoad() {
     super.viewDidLoad()

     title = "Production Tracking"
     let btn2 = UIButton(type: .custom)
     btn2.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
     btn2.addTarget(self,
     action:#selector(NativeLabelSwiftViewController.
     onBtn2Clicked.(_:)), for: .touchUpInside)
    let item2 = UIBarButtonItem(customView: btn2)

    self.navigationItem.setLeftBarButton(item2, animated: true)
  }

  @IBAction func onBtn2Clicked(_ sender: UIBarButtonItem) {
    if let navViewController = self.navigationController as? 
     NavigationController {
       // navigation view controller is available
   }
  else{
    // navigation view controller not available
  } 
}

}

导航控制器具有一个UIViewController类(NativeLabelSwiftViewController),该类在选项卡栏中具有一个按钮。按下按钮时,我需要访问导航控制器方法,但是我无法使用以下代码来获取导航控制器: -

     let navViewController = self.navigationController as? 
     NavigationController;   //this is NIL

但是

      let uiViewController = self.navigationController as? 
      UINavigationController;   //this is not NIL

1 个答案:

答案 0 :(得分:2)

您没有在AppDelegate中引用您的自定义导航控制器。您使用了UINavigationController(rootViewController: rootViewController)

如果您想使用StoryBoard NavigationController,请在AppDelegate中使用-

let nav = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NavigationController") as! NavigationController

window = UIWindow(frame: UIScreen.main.bounds)
window!.rootViewController = nav
window!.makeKeyAndVisible()
return true

注意:不要忘记为StoryBoard NavigationController放置一个标识符。