【问题标题】:navigate between xib view files在 xib 视图文件之间导航
【发布时间】:2020-12-26 05:36:17
【问题描述】:

我正在做一个项目,该项目没有故事板,它只有一个带有自己的类的 xib 文件的视图,问题是:如何在这些 xib 视图之间导航? 还是可以将它们嵌入到导航控制器中?

我尝试了这段代码,但什么也没发生?

let NC = UINavigationController()

 @IBAction func showUserProfile(_ sender: Any) {
    
    print("show Profile")
    let vc = UserProfile(
    nibName: "UserProfile",
    bundle: nil)
    NC.pushViewController(vc,
    animated: true )
}

这是在应用委托中

 let mainView = BlockListViewController(nibName: "BlockListViewController", bundle: nil)
    window?.addSubview(mainView)
    let navigationControll = UINavigationController(rootViewController: mainView)
    self.window?.rootViewController = navigationControll
    self.window?.makeKeyAndVisible()

当事件发生时,我会尝试使用它进行导航

    self.navigationController?.pushViewController(UserProfile(), animated: true)

【问题讨论】:

  • 你不能在 VC 中添加这些视图并进行导航
  • 如何在它们之间导航?我将一个设置为初始视图控制器,但我需要在这些 xib 视图之间导航
  • 检查我的答案并更新有关此评论的解决方法

标签: ios swift navigation


【解决方案1】:

您无法在 UIView 的实例之间导航

据苹果UINavigationController

一个容器视图控制器,它定义了用于导航分层内容的基于堆栈的方案。

导航控制器是一个容器视图控制器,用于管理 一个或多个子视图控制器

所以基本上是一堆UIViewController,定义为[UIViewController]

documentation了解更多信息

您可以做的是在UIViewController 中添加每个UIView,然后简单地浏览。

根据您的评论,您可以将它们预定义到 VC 实例中并使用您的初始值创建一个 UINavigationController,然后只需从 UINavigationController 推送到所需的 UIViewController

评论更新

正如我从您在主视图中的评论中得知的那样,您已经定义了 UINavigationController,只需替换 NC.pushViewController(vc,animated: true ) self.navigationController.pushViewController(vc, animated: true )

问题是您正在创建新的UINavigationController,而您已经嵌入了第一个

评论更新: 如果您使用带有场景委托的 iOS 13+,请在 willConnectTo 中使用它

   guard let scene = (scene as? UIWindowScene) else { return }
    // Instantiate UIWindow with scene
    let window = UIWindow(windowScene: scene)
    // Assign window to SceneDelegate window property
    self.window = window
    // Set initial view controller from Main storyboard as root view controller of UIWindow
    let mainView = BlockListViewController(nibName: "BlockListViewController", bundle: nil)
    let navigationControll = UINavigationController(rootViewController: mainView)

    self.window?.rootViewController = navigationControll
    // Present window to screen
    self.window?.makeKeyAndVisible()

并致电self.navigationController.push

喜欢这个

@IBAction func didTap(_ sender: UIButton)  {
        let secondView = secondVC(nibName: "secondVC", bundle: nil)
        self.navigationController?.pushViewController(secondView, animated: true)
    }

【讨论】:

  • 这是 UIVewcontroller 固有的第一个类:类 BlockListViewController: UIViewController 这是第二个视图控制器我如何将第一个嵌入到导航控制器中并从它转到第二个这些类视图作为 xib 文件不是故事板
  • 问题是(通过 xibs 导航)答案是否定的,这是一种解决方法我不知道你的代码和实际问题是什么
  • 这是 UIVewcontroller 固有的第一个类:类 BlockListViewController: UIViewController 这是第二个视图控制器我如何将第一个嵌入到导航控制器中并从它转到第二个这些类视图作为 xib 文件不是故事板——
  • 为什么不显示来自 navigationController 的第一类?如果是这种情况,请隐藏它的导航栏
  • 让 mainView = BlockListViewController(nibName: "BlockListViewController", bundle: nil) let navigationControll = UINavigationController(rootViewController: mainView)