NavigationController没有看到右侧栏按钮项

时间:2017-08-25 22:20:02

标签: swift

我试图通过允许用户添加算命应用的新结果来了解演示视图控制器。当用户点击"添加新结果"在导航栏的右上角会弹出一个新的视图控制器,这是用户可以输入新结果的位置。我尝试在演示控制器的右上角添加一个完成按钮,但我收到错误Value of type 'UINavigationController?' has no member 'rightBarButtonItem'

我认为是因为引用topViewController是问题,但我在1个ViewController中完成了这一操作。

@IBAction func actionButtonTapped(_ sender: UIBarButtonItem) {
    let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

    let viewController = storyboard.instantiateViewController(withIdentifier: "AddNewOptionController")
    viewController.modalPresentationStyle = .popover
    let popover : UIPopoverPresentationController = viewController.popoverPresentationController!
    popover.barButtonItem = sender
    popover.delegate = self
    present(viewController, animated: true, completion: nil)
}

func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
    return .fullScreen
}

func presentationController(_ controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? {
    let navigationController = UINavigationController(rootViewController: controller.presentedViewController)
    let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(ViewController.dismissViewController))
//error below
     navigationController.topViewController?.navigationController.rightBarButtonItem = doneButton
    return navigationController
}

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

2 个答案:

答案 0 :(得分:2)

而不是:

navigationController.topViewController?.navigationController.rightBarButtonItem = doneButton

尝试:

navigationController.topViewController?.navigationItem.rightBarButtonItem = doneButton

答案 1 :(得分:0)

您可以使用此代码:

self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named:"YOUR_IMAGE_NAME"), style: .plain, target: self, action: #selector(YOUR_FUNCTION))

希望这对你有用