创建一个类继承自UIButton
import UIKit
class TitleAndImageButton: UIButton {
override init(frame: CGRect) {
super .init(frame: frame)
setUpUI()
}
//通过XIB/SB创建时调用
required init?(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
super.init(coder: aDecoder)
setUpUI()
}
func setUpUI() {
setImage(UIImage.init(named: "navigationbar_arrow_down"), for: .normal)
setImage(UIImage.init(named: "navigationbar_arrow_up"), for: .selected)
setTitleColor(UIColor.gray, for: .normal)
setTitleColor(UIColor.orange, for: .selected)
adjustsImageWhenHighlighted = false
sizeToFit()
}
override func setTitle(_ title: String?, for state: UIControl.State) {
super.setTitle((title ?? "") + " ", for: state)
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel?.frame.origin.x = 0
imageView?.frame.origin.x = titleLabel!.frame.width
}
}
调用的时候
let titleBtn = TitleAndImageButton() //如果需要尺寸,自己换成frame的
titleBtn.setTitle("标题展示", for: .normal)
titleBtn.addTarget(self, action: #selector(titleBtnClick(_:)), for: .touchUpInside)
@objc private func titleBtnClick(_ btn : UIButton) {
btn.isSelected = !btn.isSelected
}
这样就可以了
然后图片和文字都可以在外边用系统方法替换掉