利用构造函数设置导航栏
给 UIBarButtonItem 添加扩展类UIBarButtonItem-Extension
import UIKit
extension UIBarButtonItem {
/*
class func createItem(imageName : String, highImageName : String, size : CGSize) -> UIBarButtonItem {
let btn = UIButton()
btn.setImage(UIImage(named: imageName), forState: .Normal)
btn.setImage(UIImage(named: highImageName), forState: .Highlighted)
btn.frame = CGRect(origin: CGPointZero, size: size)
return UIBarButtonItem(customView: btn)
}
*/
// 便利构造函数: 1> convenience开头 2> 在构造函数中必须明确调用一个设计的构造函数(self)
convenience init(imageName : String, highImageName : String = "", size : CGSize = CGSize.zero) {
// 1.创建UIButton
let btn = UIButton()
// 2.设置btn的图片
btn.setImage(UIImage(named: imageName), for: UIControlState())
if highImageName != "" {
btn.setImage(UIImage(named: highImageName), for: .highlighted)
}
// 3.设置btn的尺寸
if size == CGSize.zero {
btn.sizeToFit()
} else {
btn.frame = CGRect(origin: CGPoint.zero, size: size)
}
// 4.创建UIBarButtonItem
self.init(customView : btn)
}
}
然后在控制器中创建自定义 item
fileprivate func setupNavigationBar() {
// 1.设置左侧的Item
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo")
// 2.设置右侧的Item
let size = CGSize(width: 40, height: 40)
let historyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size)
let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size)
let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size)
navigationItem.rightBarButtonItems = [historyItem, searchItem, qrcodeItem]
}