import UIKit
class CustomBtn: UIButton {
//MARK:- 重写init函数
override init(frame: CGRect) {
super.init(frame: frame)
setImage(UIImage(named:"navigationbar_arrow_up"), for: .normal)
setImage(UIImage(named:"navigationbar_arrow_down"), for: .selected)
setTitleColor(UIColor.black, for: .normal)
backgroundColor = UIColor.cyan
}
//swift中规定:重写控件的init(frame方法)或者init()方法.必须重写 init?(coder aDecoder: NSCoder)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
//titleLabel ,imageView中间的空隙宽度
let spaceWid = CGFloat(5)
//btn的宽度
let btnWid = frame.size.width
//titleLabel ,imageView的总宽度 加 空隙
let wid = titleLabel!.frame.size.width + imageView!.frame.size.width + spaceWid
titleLabel!.frame.origin.x = (btnWid-wid)*0.5
imageView!.frame.origin.x = titleLabel!.frame.maxX + spaceWid
}
}
在ViewController中调用
import UIKit
class ViewController: UIViewController {
lazy var btn : CustomBtn = CustomBtn()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
//MARK:- 创建UI
extension ViewController{
func setupUI(){
btn.frame = CGRect(x: 0, y: 0, width: 100, height: 50)
btn.setTitle("皮皮鳝", for: .normal)
btn.center = view.center
btn.addTarget(self, action: #selector(ViewController.btnClick(sender:)), for: .touchUpInside)
view.addSubview(btn)
}
}
//MARK:- 事件监听
extension ViewController{
@objc fileprivate func btnClick(sender:UIButton) {
sender.isSelected = !sender.isSelected
}
}
效果图: