首页 > 解决方案 > 从 navigationStack 中移除 ViewController 并添加它的新实例

问题描述

我有一个嵌入了 navigationController 的 SongNamesViewController。当从列表中选择一首歌曲时,我打开 PlaySongViewController 并使用以下函数添加到 navigationController:

func openPlaySongViewController() {     
  let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
  let playSongViewController = storyBoard.instantiateViewController(withIdentifier: "playSongViewController")
     self.navigationController?.pushViewController(playSongViewController, animated: true)
}

现在,一条消息通过远程推送通知到达。用户点击推送通知图标,然后我使用“openPlaySongViewController()”函数显示歌曲。如果另一个推送通知出现,然后我在现有 PlaySongViewController 之上显示另一个 PlaySongViewController。

电流:(NavigationController)->SongNamesViewController>PlaySongViewController->PlaySongViewController

在添加新的 PlaySongViewController 实例之前,如何删除 navigationController 上现有的 PlaySongViewController?

我尝试了以下方法,但 navigationController 上的 PlaySongViewController 并没有消失。

for viewController in self.navigationController!.viewControllers {                
     if viewController.isKind(of: PlaySongViewController.self) {                   
          viewController.removeFromParent()                                 
     }
}

标签: swiftnavigationcontroller

解决方案


topViewController返回导航堆栈顶部的内容。pop因此,如果需要,您应该这样做。

func removeLastControllerIfNeeded() {
    guard navigationController?.topViewController is PlaySongViewController else { return }
    navigationController?.popViewController(animated: true)
}

推荐阅读