一、场景描述:
- 情景1:image尺寸比button大,直接设置AspectFill
- 情景2:image尺寸比button小,默认会居中显示且不会充满整个button,如果希望充满整个button需要自定义button并重写imageRect方法,参见以下代码。
图片在左文字在右结构的button示例
import UIKit
class RTSettingBtn: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setImage(UIImage(named:"L_set"), for: UIControl.State.normal)
titleLabel?.textAlignment = NSTextAlignment.center
titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium)
setTitle("设置", for: UIControl.State.normal)
setTitleColor(UIColor.black, for: UIControl.State.normal)
let space = 10
titleEdgeInsets = UIEdgeInsets(top: 0, left: space/2.0, bottom: 0, right: -space/2.0)
imageEdgeInsets = UIEdgeInsets(top: 0, left: -space/2.0, bottom: 0, right: space/2.0)
imageView?.contentMode = .scaleAspectFill
sizeToFit()
}
override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
return CGRect(x: 0, y: 0, width: self.height, height: self.height)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
}
}
二、oc参考
oc实现-UIButton设置imgae图片自适应button的大小且不变形