我正在尝试将UIBarButton项添加到导航栏。
这是我的导航栏类声明:
import UIKit
class NavigationBarController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
configureToolbar()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Navigation bar data source
func configureToolbar() {
let toolbarButtonItems = [
searchBarButtonItem
]
toolbar.setItems(toolbarButtonItems, animated: true)
}
var searchBarButtonItem: UIBarButtonItem {
return UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "barButtonItemClicked:")
}
}
编译器没有错误,但我得到的只是一个简单的导航栏。
如何显示UIBarButtonItem?
答案 0 :(得分:35)
要将项目添加到NavigationBar
的{{1}}或添加到NavigationController
的{{1}},您需要首先浏览NavigationBar
。试试这个:
ViewController
要将按钮切换到左侧,只需将NavigationItem
替换为self.navigationItem.setRightBarButtonItems(navigationBarButtonItemsArray, animated: true)
// Or if you just want to insert one item.
self.navigationItem.setRightBarButtonItem(UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "barButtonItemClicked:"), animated: true)
或setRightBarButtonItem
。
答案 1 :(得分:6)
您可以在导航栏的右侧或左侧添加多个按钮。 我会告诉你在右侧添加你也可以为左侧做同样的事情
override func viewDidLoad()
{
let Nam1BarBtnVar = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: #selector(Nam1BarBtnKlkFnc(_:)))
let Nam2BarBtnVar = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(Nam2BarBtnKlkFnc(_:)))
self.navigationItem.setRightBarButtonItems([Nam1BarBtnVar, Nam2BarBtnVar], animated: true)
}
func Nam1BarBtnKlkFnc(BtnPsgVar: UIBarButtonItem)
{
print("Nam1BarBtnKlk")
}
func Nam2BarBtnKlkFnc(BtnPsgVar: UIBarButtonItem)
{
print("Nam2BarBtnKlk")
}
答案 2 :(得分:2)
针对Swift 3进行了更新:
使用以下代码以编程方式添加UIBarButton项目。
添加左栏按钮:
y-axis
添加右侧栏按钮:
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "your_image_name"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(yourViewControllerName.barButtonClickAction))
方法定义:
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "your_image_name"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(yourViewControllerName.barButtonClickAction))