Swift5-UIButton设置image图片自适应butto

2020-05-19  本文已影响0人  Jesscia_Liu

一、场景描述:

图片在左文字在右结构的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的大小且不变形

上一篇 下一篇

猜你喜欢

热点阅读