titleButton是系统不能满足需求而且自己封装的button。
import UIKit
class TitleButton: UIButton {
override init(frame : CGRect) {
super.init(frame: frame)
setImage(UIImage(named: "tabbar_discover"), for: .normal)
setImage(UIImage(named: "tabbar_discover_selected"), for: .selected)
setTitleColor(UIColor.black, for: .normal)
sizeToFit()
}
// 必须实现
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel!.frame.origin.x = 0
imageView!.frame.origin.x = titleLabel!.frame.size.width + 5
}
}
创建好titleButton之后使用titleButton
let titleBtn : TitleButton = TitleButton()
titleBtn.setTitle("txwDemo", for: .normal)
titleBtn.addTarget(self, action: #selector(OneVC.titleBtnClick), for: .touchUpInside)
navigationItem.titleView = titleBtn
// 监听标题按钮点击
extension OneVC {
func titleBtnClick(titleBtn :TitleButton){
// 改变按钮状态
titleBtn.isSelected = !titleBtn.isSelected
//
let vc = UIViewController()
self.present(vc, animated: true, completion: nil)
}
}