从NavigationStack中删除ViewController并为其添加新实例

问题描述 投票:1回答:2

我有一个嵌入了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()                                 
     }
}
swift navigationcontroller
2个回答
0
投票

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

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

0
投票

如果需要从堆栈中删除所有名为PlaySongViewController的vc,请执行

for vc in self.navigationController!.viewControllers {                
     if vc is SongNamesViewController {                   
          self.navigationcontroller?.popToViewController(vc,animated:true)
          break                                 
     }
}

[如果根在任何时候都是SongNamesViewController,那么您也可以这样做

self.navigationcontroller?.popToRootViewController(animated:true)
© www.soinside.com 2019 - 2024. All rights reserved.