【问题标题】:UIBarButtonItem is not working swift 3.0UIBarButtonItem 无法快速运行 3.0
【发布时间】:2017-10-02 00:42:44
【问题描述】:

我有一个导航控制器,我试图在导航栏右侧放置一个按钮,但我无法处理点击操作。我像这样声明 UIBarButtonItem

let navigationButton = UIBarButtonItem.init(title: "Logout", style: .done, target: self, action: #selector(RestaurantsListViewController.logoutAction))

我正在 viewDidLoad 函数上添加按钮

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.rightBarButtonItem = navigationButton
}

我试图用来处理点击事件的函数就是这个

func logoutAction(sender: AnyObject?){
    print("Logout")
}

但是当我按下按钮时,消息不会打印在控制台中。

【问题讨论】:

  • 让 navigationButton = UIBarButtonItem.init(title: "Logout", style: .done, target: self, action: #selector(RestaurantListViewController.logoutAction)) 在视图中确实加载了..?
  • 你在哪个控制器中写了logoutAction函数?
  • @AnilKumar 我在主类上有初始化器,在所有方法中
  • @BalajiGalave 我都在同一个视图控制器中
  • 然后试试我在下面发布的答案。还有一件事尝试在视图控制器的 viewWillAppear 方法中为 Navigationbar 设置按钮。这是添加的好地方。

标签: ios swift


【解决方案1】:

试试这个:

override func viewDidLoad() {
     super.viewDidLoad()

self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "ButtonName", style: .done, target: self, action: #selector(YourViewController.yourAction))

}

【讨论】:

  • Initialize UIBarButtonItem inside viewDidLoad func 修复问题,谢谢!
【解决方案2】:
  let okbtn = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.logoutAction))

试试这个 否则你需要像这样替换func

func logoutAction()
{
  print("logout")
}

【讨论】:

    【解决方案3】:

    这里的问题是,当您将 navigationButton 创建为类属性时,它会在 self 被初始化之前被初始化。因此,当您将 self 作为按钮的 target 传递时,它还不存在。

    有几种方法可以修复它,包括@Mannopson 的回答,您在其中初始化viewDidLoad 内的按钮,这确保self 已经创建。

    解决此问题的另一种方法是将navigationButton 声明为lazy var

    lazy var navigationButton = UIBarButtonItem.init(title: "Logout", style: .done, target: self, action: #selector(RestaurantsListViewController.logoutAction))
    

    lazy var 确保属性仅在属性被访问时才被初始化(因此它是延迟初始化)。由于第一次访问发生在viewDidLoad,我们也可以确定self 已经创建。希望这可以为您提供更多背景信息!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      • 2017-04-02
      • 2015-09-14
      • 2015-02-18
      • 1970-01-01
      • 2018-04-13
      • 2020-11-26
      相关资源
      最近更新 更多