[swift4.2] iOS中UIButton继承类,文字与图片位置上下左右排列

WX20190320-103412.png
// swift4.2 UIButton扩展,文字与图片位置上下左右排列
class LayoutButton: UIButton {
 
    enum Position {
        case top
        case bottom
        case left
        case right
    }
    
    private var position: Position?   // 图片相对文字的位置
    private var space: CGFloat = 0    // 图片相对文字的间距
    
    convenience init(_ position: Position, space: CGFloat = 0) {
        self.init(type: .custom)
        self.position = position
        self.space = space
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        if let position = position {
            switch position {
            case .top:
                let titleHeight = titleLabel?.bounds.height ?? 0
                let imageHeight = imageView?.bounds.height ?? 0
                let imageWidth = imageView?.bounds.width ?? 0
                let titleWidth = titleLabel?.bounds.width ?? 0
                titleEdgeInsets = UIEdgeInsets(top: (titleHeight + space) * 0.5, left: -imageWidth * 0.5, bottom: -space, right: imageWidth * 0.5)
                imageEdgeInsets = UIEdgeInsets(top: 0, left: titleWidth * 0.5, bottom: imageHeight + space, right: -titleWidth * 0.5)
            case .bottom:
                let titleHeight = titleLabel?.bounds.height ?? 0
                let imageHeight = imageView?.bounds.height ?? 0
                let imageWidth = imageView?.bounds.width ?? 0
                let titleWidth = titleLabel?.bounds.width ?? 0
                titleEdgeInsets = UIEdgeInsets(top: -(titleHeight + space) * 0.5, left: -imageWidth * 0.5, bottom: space, right: imageWidth * 0.5)
                imageEdgeInsets = UIEdgeInsets(top: imageHeight + space, left: titleWidth * 0.5, bottom: -titleWidth * 0.5, right: 0)
            case .left:
                titleEdgeInsets = UIEdgeInsets(top: 0, left: space, bottom: 0, right: 0)
                titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: space)
            case .right:
                let imageWidth = (imageView?.bounds.width ?? 0) + space
                let titleWidth = (titleLabel?.bounds.width ?? 0) + space
                titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageWidth, bottom: 0, right: imageWidth)
                imageEdgeInsets = UIEdgeInsets(top: 0, left: titleWidth, bottom: 0, right: -titleWidth)
            }
        }
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容