IOS App开发难免会遇到导航栏右上角需要显示2个按钮的时候,今天就讲一下Swift在导航栏左侧或者右侧放置多个按钮例子,使用 navigationItem.leftBarButtonItem 和 navigationItem.rightBarButtonItem 可以很方便的分别设置导航栏左侧和右侧按钮,但一侧只能有一个按钮。如果想要在一侧使用多个按钮,可以通过 leftBarButtonItems 和 rightBarButtonItems 来实现。

设置按钮

override func viewDidLoad(){
super.viewDidLoad()

//navitem search 搜索按钮
let buttonSearch = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 20, height: 20))
buttonSearch.setImage(UIImage.init(named: "home_navitem_search"), for: UIControlState.normal)
buttonSearch.addTarget(self, action: #selector(navigationItemSearchAction), for: UIControlEvents.touchUpInside)
let barButtonSearch = UIBarButtonItem(customView: buttonSearch)

//navitem 客服按钮
let buttonService = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 20, height: 20))
buttonService.setImage(UIImage.init(named: "customer_service"), for: UIControlState.normal)
buttonService.addTarget(self, action: #selector(navigationItemServiceAction), for: UIControlEvents.touchUpInside)
let barButtonService = UIBarButtonItem(customView: buttonService)

//按钮间的空隙
let gap = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil)
gap.width = 12;

//用于消除右边边空隙,要不然按钮顶不到最边上
let spacer = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil)
spacer.width = -5;

//设置按钮(注意顺序)
self.navigationItem.rightBarButtonItems = [spacer, barButtonSearch, gap, barButtonService]

点击事件

//搜索
@objc func navigationItemSearchAction() {
print("搜索按钮点击")
}

//客服
@objc func navigationItemServiceAction() {
print("客服按钮点击")
}