这是使用系统的方法
var img = UIImage(named: "max")
let item = UIBarButtonItem(image: img, style: UIBarButtonItemStyle.Plain, target: self, action: nil)
self.navigationItem.rightBarButtonItem = item
下面是使用自定义的方法
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//搜索按钮
let button1 = UIButton(frame:CGRect(x:0, y:0, width:18, height:18))
button1.setImage(UIImage(named: "search"), for: .normal)
button1.addTarget(self,action:#selector(tapped1),for:.touchUpInside)
let barButton1 = UIBarButtonItem(customView: button1)
//设置按钮
let button2 = UIButton(frame:CGRect(x:0, y:0, width:18, height:18))
button2.setImage(UIImage(named: "settings"), for: .normal)
button2.addTarget(self,action:#selector(tapped2),for:.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()
}
}
网友评论