Swift:为UINavigationController工具栏添加工具栏按钮时遇到问题

问题描述:

我在嵌入导航控制器的我的子类UIViewController中覆盖了以下viewDidLoad。我已经隐藏了工具栏,当我运行时,工具栏就在那里(确认我在导航控制器内,并且我正确地处理它),但我无法显示任何按钮。我在这里做错了什么?Swift:为UINavigationController工具栏添加工具栏按钮时遇到问题

override func viewDidLoad() { 
    super.viewDidLoad() 

    var buttons = [UIBarButtonItem]() 
    for title in buttonTitleArray { 
     let plainButton = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(self.setContentMode(_:))) 
     let systemButton = UIBarButtonItem(barButtonSystemItem: .play, target: self, action: #selector(self.setContentMode(_:))) 
     buttons.append(plainButton) 
     buttons.append(systemButton) 
    } 
    self.navigationController?.toolbarItems = buttons 
    self.navigationController?.isToolbarHidden = false 
} 

我试过使用self.navigationController?.setToolbarItems(buttons, animated: false)添加按钮,但那也行不通。

+0

你尝试导航栏或导航栏上设置工具栏上添加按钮(自定义/系统)? –

+0

我试图在窗口底部添加一个工具栏。如果我对添加的两个不同按钮感到困惑,那么我会这样做,因为我之前没有使用过工具栏按钮,所以我想看看这个简单的按钮是什么。换句话说,你可以忽略我为每个标题制作两个按钮的事实。 –

请尝试以下代码在视图中显示的工具栏按钮: -

var items = [UIBarButtonItem]() 

    //Custom Button 
    let plainButton = UIBarButtonItem(title: "Test", style: .Plain, target: self, action: #selector(self.customButtonTapped)) 
    items.append(plainButton) 

    //Add Flexible space between buttons 
    let flexibalSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil) 
    items.append(flexibalSpace) 

    //Toolbar system button 
    let systemButton = UIBarButtonItem(barButtonSystemItem: .Play, target: self, action: #selector(self.systemButtonTapped)) 
    items.append(systemButton) 

    self.toolbarItems = items //Display toolbar items. 
    self.navigationController?.toolbarHidden = false 
+0

谢谢。它看起来像我的问题是将按钮添加到navigationController.toolbarItems而不是self.toolBarItems –