1.新建文件创建分类
//
// UIBarButtonItem+Category.swift
import UIKit
extension UIBarButtonItem{
/**
返回一个UIBarButtonItem
- parameter imageName: 图片名称
- parameter target: 目标
- parameter action: 监听方法
- returns: UIBarButtonItem
*/
// 如果在func前面加上"class",就相当于OC中的 +
class func createBarButtonItem(imageName:String, target:AnyObject, action:Selector) -> UIBarButtonItem{
let btn = UIButton()
btn.setImage(UIImage(named: imageName), forState: UIControlState.Normal)
btn.setImage(UIImage(named: imageName + "_highlighted"), forState: UIControlState.Highlighted)
btn.addTarget(target, action: action, forControlEvents: UIControlEvents.TouchUpInside)
btn.sizeToFit()
return UIBarButtonItem(customView: btn)
}
}
2.使用这个分类
/**
初始化导航条
*/
private func setupNav(){
navigationItem.leftBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_friendattention",target: self,action:#selector(HomeTableViewController.leftItemClick))
navigationItem.rightBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_pop",target: self,action: #selector(HomeTableViewController.rightItemClick))
}
func leftItemClick(){
print(#function)
}
func rightItemClick(){
print(#function)
}