UIBarButtonItem 取决于演示文稿。斯威夫特3

UIBarButtonItem depending on presentation. Swift3

我遇到了一个问题,因为有两种方法可以显示我的 ViewController

  1. 第一种方式是performSegue(withIdentifier: "segue", sender: self)

它工作正常,因为我在 navigationItem:

中有这个后退按钮

  1. 然后我使用此代码呈现相同的 ViewController(来自另一个 viewController,而不是第一种情况):

        let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let navVC = storyboard.instantiateViewController(withIdentifier: "navViewController") as! UINavigationController
        let vc = navVC.topViewController as! ViewController             
        self.present(navVC, animated: true, completion: nil)
    

但是我 ViewController.

中没有任何后退按钮

我的问题是: 当我使用此功能时如何保留我的 backButton (exactly how it is)performSegue(withIdentifier: "segue", sender: self),但添加按钮(可以看起来不同)我使用这个函数:self.present(navVC, animated: true, completion: nil)

注意: 在我的案例 1 中,我的 segue 直接连接到 ViewController ,但在案例 2 中,我提供了 UINavigationControllerViewController在这个UINavigationController.

中是embed in

编辑: 我试过这段代码,但它总是打印:"1.........":

if self.presentingViewController != nil {
            print("1..........")
        } else if self.navigationController?.presentingViewController?.presentedViewController == self.navigationController  {
            return print("2.........")
        } else if self.tabBarController?.presentingViewController is UITabBarController {
            return print("3........")
        }

并且此代码还打印:"Else.............." :

let isPresentingInAddMealMode = presentedViewController is UINavigationController

if isPresentingInAddMealMode {
    print("FirstOption......................")

} else {
    print("Else......................")

}

如果您需要更多信息,请告诉我。 非常感谢。

您需要检查 presentedViewController 并添加后退按钮,如下所示。

if ([self presentedViewController]) {
        // add your back button item here
    }

试试这个:

let viewController = storyboard?.instantiateViewController(withIdentifier: "Login") as! LoginView
let customNavigation = UINavigationController(rootViewController: viewController)
customNavigation.navigationBar.tintColor = UIColor.black
self.present(customNavigation, animated: true, completion: nil)

override func viewDidLoad() {
    super.viewDidLoad()
    self.title = "Login"
    navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "back"), style: .plain, target: self, action: #selector(self.backButton))

}
func backButton() {
    self.dismiss(animated: true, completion: nil)
}

尝试在 UIBarButtonItem 中设置 Image

我解决了!!我把 restorationIdentifier 放到我的根目录 navigationController 中,然后我用我的 restorationIdentifier 检查它是否是 navigationController 像这样:

    if self.navigationController?.restorationIdentifier == "navViewController"{
        let leftItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(goBack))
        self.navigationItem.leftBarButtonItem = leftItem //Adds item if id is navViewController
    }else{
       self.navigationItem.leftBarButtonItem = nil //removes it and keeps "<Back"
    }