ios - 无法以编程方式添加栏按钮项

标签 ios swift cocoa-touch uinavigationbar

func myPlaceViewMoreWasPressed() {
    print("myPlaceViewMore was pressed")

    let vc = MyPlacesViewController(nil)
    let nav = UINavigationController(rootViewController: vc)
    let dismissButton = UIBarButtonItem.init(title: "Dismiss", style: .plain, target: self, action: #selector(dismissButtonWasPressed))
    nav.navigationItem.leftBarButtonItem = dismissButton

    self.present(nav, animated: true, completion: nil)
}

应该非常简单...实例化一个 ViewController,将其包含在导航 Controller 中,初始化一个 UIBarButtonItem 并将其设置为导航的 leftBarButtonItem。我也试过这样:

func myPlaceViewMoreWasPressed() {
    print("myPlaceViewMore was pressed")

    let vc = MyPlacesViewController(nil)
    let nav = UINavigationController(rootViewController: vc)
    let dismissButton = UIBarButtonItem.init(title: "Dismiss", style: .plain, target: self, action: #selector(dismissButtonWasPressed))
    nav.navigationItem.setLeftBarButton(dismissButton, animated: true)

    self.present(nav, animated: true, completion: nil)
}

但是按钮不会出现。

最佳答案

您需要更新 View Controller 的 navigationItem,而不是导航 Controller 。我会在将 View Controller 设置为根 Controller 之前这样做。

func myPlaceViewMoreWasPressed() {
    print("myPlaceViewMore was pressed")

    let vc = MyPlacesViewController(nil)
    let dismissButton = UIBarButtonItem.init(title: "Dismiss", style: .plain, target: self, action: #selector(dismissButtonWasPressed))
    vc.navigationItem.leftBarButtonItem = dismissButton

    let nav = UINavigationController(rootViewController: vc)

    self.present(nav, animated: true, completion: nil)
}

关于ios - 无法以编程方式添加栏按钮项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43191150/

相关文章:

ios - tvOS - 无法连接到本地主机

ios - MT5202 : Native linking failed - Xamarin. iOS 7 - 外部附件

ios - 导航弹出 View Controller 时如何更改动画方向

ios - UITextField 输入不工作

iphone - 先学习 Leopard 的 Cocoa 然后再学习 iPhone 的 Cocoa Touch 有意义吗?

objective-c - iPhone 中真正的模态 UIAlertView?

ios - CoreData 和对象处理的建议

android - iOS 和 Android 中 WebView 的总缓存大小是多少?

ios - 如何使用 Carthage 构建针对 ARM 和 x86 目标的框架?

iphone - COCOS2D : ScrollView inside a CCScene blocks animation