美文网首页
[swift4.2] iOS中UIButton继承类,文字与图片

[swift4.2] iOS中UIButton继承类,文字与图片

作者: 亡鱼 | 来源:发表于2019-03-20 10:32 被阅读0次
    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)
                }
            }
        }
    
    }
    

    相关文章

      网友评论

          本文标题:[swift4.2] iOS中UIButton继承类,文字与图片

          本文链接:https://www.haomeiwen.com/subject/cxaamqtx.html