使用 navigationItem.leftBarButtonItem 和 navigationItem.rightBarButtonItem 可以很方便的分别设置导航栏左侧和右侧按钮,但一侧只能有一个按钮。
如果想要在一侧使用多个按钮,可以通过 leftBarButtonItems 和 rightBarButtonItems 来实现。
下面演示给导航栏右侧添加两个按钮(搜索和设置):
同时两个按钮间设置了间距,并将设置按钮顶到边上。
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//搜索按钮
let button1 = UIButton(frame:CGRectMake(0, 0, 18, 18))
button1.setImage(UIImage(named: "search"), forState: .Normal)
button1.addTarget(self,action:Selector("tapped1"),forControlEvents:.TouchUpInside)
let barButton1 = UIBarButtonItem(customView: button1)
//设置按钮
let button2 = UIButton(frame:CGRectMake(0, 0, 18, 18))
button2.setImage(UIImage(named: "settings"), forState: .Normal)
button2.addTarget(self,action:Selector("tapped2"),forControlEvents:.TouchUpInside)
let barButton2 = UIBarButtonItem(customView: button2)
//按钮间的空隙
let gap = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil,
action: nil)
gap.width = 15;
//用于消除右边边空隙,要不然按钮顶不到最边上
let spacer = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil,
action: nil)
spacer.width = -10;
//设置按钮(注意顺序)
self.navigationItem.rightBarButtonItems = [spacer,barButton2,gap,barButton1]
}
func tapped1(){
print("搜索按钮点击")
}
func tapped2(){
print("设置按钮点击")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
好了以上就是关于ios开中导航栏的放多个按钮的例子。