UIButton - Image & Label Posisti
2020-05-08 本文已影响0人
ienos
三个参数
imageEdgeInsets、titleEdgeInsets、contentEdgeInset
Content
UIButton
的 Content
包括: Image
和 Label
Content Height = Maximum(Image.height, Label.height)
Content Width = Image Width + Label Width
image 和 label centerY 是相同的
默认 image 在左边,label 在右边
Image Left / Label Right
image.pngImage Right / Label Left
image.pngImage Top / Label Bottom
image.pngImage Bottom / Label Top
image.pngSwift 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
}
}
}