ios - 返回根导航 Controller 的按钮

标签 ios swift

我正在使用 Storyboard并拥有 3 个 VC。当我使用 VC3 时,我希望后退按钮可以跳过 VC2 并转到 VC1。

我尝试了以下方法,但 VC2 在到达 VC1 之前闪烁

override func viewWillDisappear(_ animated: Bool) {
    self.navigationController?.popViewController(animated: true)
}

我的自定义返回代码:

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
    self.navigationController?.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.isTranslucent = true
    self.navigationController?.navigationBar.backIndicatorImage = UIImage(named: "arrow_back")
    self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "arrow_back")
    self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: #selector(self.backPressed(_:)))
    self.navigationController?.navigationBar.barStyle = .black  
}

@objc func backPressed(_ sender: Any){
    print("here")
    self.navigationController?.popToRootViewController(animated: false)
}

最佳答案

viewDidLoad 的变化

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
    self.navigationController?.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.isTranslucent = true
    self.navigationController?.navigationBar.backIndicatorImage = UIImage(named: "arrow_back")
    self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "arrow_back")

     var backButton = UIBarButtonItem(title: "", style: .plain, target: self, action: #selector(backPressed(_:)))
     navigationController?.navigationBar.topItem?.backBarButtonItem = backButton
    self.navigationController?.navigationBar.barStyle = .black  
}

添加 如果你想首先使用 Controller

@objc func backPressed(_ sender: Any){
     self.navigationController?.popToRootViewController(animated: true) 
}

如果它不是导航 Controller 中的第一个 View Controller

@objc func backPressed(_ sender: Any){
     let controllerToBeReached = navigationController!.viewControllers.filter { $0 is YourViewController }.first!
     navigationController!.popToViewController(controllerToBeReached, animated: true)
}

关于ios - 返回根导航 Controller 的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58128258/

相关文章:

ios - 准备(对于segue : UIStoryboardSegue,发件人: Any?)不在Xcode 8.1 swift 3 ios 10中触发

PHP-iOS 带图像的推送通知

iphone - 尝试构建时添加可达性类失败

ios - 使用 swift 连接 UIImageView 以查看 Images.xcassets 中的 Controller 显示图像

ios - 如何摆脱 Swift 字符串中的 "non-breaking space"?

ios - 如何在 objective-c 中以编程方式更改字体样式

ios - calayer 没有根据 tableview 单元格中的 UIView 大小而改变

ios - UIButton 将目标添加到不同的 View Controller

ios - 如何检测 UIScrollView 何时在 Swift 中完成滚动

swift - 以编程方式为 UITextField 创建 .touchUpInside 事件