swift微博第8天(自定义标题按钮)
2017-06-01 本文已影响34人
IIronMan
1.自定义一个TittleBtn
import UIKit
class TittleBtn: UIButton {
// 初始化视图
override init(frame: CGRect) {
super.init(frame: frame)
setTitleColor(UIColor.JKTextGayColor(), for: UIControlState.normal)
setImage(UIImage(named:"navigationbar_arrow_down"), for: UIControlState.normal)
setImage(UIImage(named:"navigationbar_arrow_up"), for: UIControlState.selected)
sizeToFit()
}
// 防止storyboard崩溃
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 调整图片和文字的位置
override func layoutSubviews() {
super.layoutSubviews()
titleLabel?.x = 0
imageView?.x = titleLabel!.width
}
}
提醒:我这里可以用.x
和.with
是因为我对frame
进行了重写
2.调用自定义的标题按钮
let btn = TittleBtn()
btn.setTitle("极客江南 ", for: UIControlState.normal)
btn.addTarget(self, action: #selector(HomeViewController.tittleClick(btn:)), for: UIControlEvents.touchUpInside)
navigationItem.titleView = btn
3.方法的实现
@objc private func tittleClick(btn:TittleBtn){
print("标题的点击方法")
btn.isSelected = !btn.isSelected
}