UIKit

UIButton - Image & Label Posisti

2020-05-08  本文已影响0人  ienos

三个参数

imageEdgeInsets、titleEdgeInsets、contentEdgeInset

Content

UIButtonContent 包括: ImageLabel

  1. Content Height = Maximum(Image.height, Label.height)
  2. Content Width = Image Width + Label Width
image.png

image 和 label centerY 是相同的

默认 image 在左边,label 在右边

Image Left / Label Right

image.png

Image Right / Label Left

image.png

Image Top / Label Bottom

image.png

Image Bottom / Label Top

image.png

Swift Code

extension UIButton {
    
    enum ImageTextAlignment {
        case ImageTop
        case ImageLeft
        case ImageRight
        case ImageBottom
    }
    
    func setImageTextAlignmentPosition(_ position: ImageTextAlignment, space: CGFloat) {
        
        let imageW: CGFloat = self.imageView?.image?.size.width ?? CGFloat(0)
        let imageH: CGFloat = self.imageView?.image?.size.height ?? CGFloat(0)

        let titleW: CGFloat = self.titleLabel?.width ?? CGFloat(0)
        let titleH: CGFloat = self.titleLabel?.height ?? CGFloat(0)
        
        let contentW: CGFloat = imageW + titleW
        
        switch position {
        case .ImageTop:
            imageEdgeInsets = UIEdgeInsets(top: -(space * 0.5 + imageH * 0.5), left: (contentW * 0.5 - imageW * 0.5) , bottom: (space * 0.5 + imageH * 0.5), right: -(contentW * 0.5 - imageW * 0.5))
            titleEdgeInsets = UIEdgeInsets(top: (space * 0.5 + titleH * 0.5), left: -(imageW * 0.5), bottom: -(space * 0.5 + titleH * 0.5), right: (imageW * 0.5))
            break
        case .ImageBottom:
            imageEdgeInsets = UIEdgeInsets(top: (space * 0.5 + imageH * 0.5), left: (contentW * 0.5 - imageW * 0.5), bottom: -(space * 0.5 + imageH * 0.5), right: -(contentW * 0.5 - imageW * 0.5))
            titleEdgeInsets = UIEdgeInsets(top: -(space * 0.5 + titleH * 0.5), left: -(imageW * 0.5), bottom: (space * 0.5 + titleH * 0.5), right: (imageW * 0.5))
            break
        case .ImageLeft:
            imageEdgeInsets = UIEdgeInsets(top: 0, left: -space * 0.5, bottom: 0, right: space * 0.5)
            titleEdgeInsets = UIEdgeInsets(top: 0, left: space * 0.5, bottom: 0, right: -space * 0.5)
            break
        case .ImageRight:
            imageEdgeInsets = UIEdgeInsets(top: 0, left: (space * 0.5) + titleW, bottom: 0, right: -((space * 0.5) + titleW))
            titleEdgeInsets = UIEdgeInsets(top: 0, left: -((space * 0.5) + imageW), bottom: 0, right: ((space * 0.5) + imageW))
            break
        
        }

    }
    
}

上一篇 下一篇

猜你喜欢

热点阅读