extension UIButton {
func centerVertically(padding: CGFloat = 6.0) {
guard
let imageViewSize = self.imageView?.frame.size,
let titleLabelSize = self.titleLabel?.frame.size else {
return
}
self.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15)
self.titleLabel?.adjustsFontSizeToFitWidth = true
let totalHeight = imageViewSize.height + titleLabelSize.height + padding
self.imageEdgeInsets = UIEdgeInsets(
top: -(totalHeight - imageViewSize.height),
left: 0.0,
bottom: 0.0,
right: -titleLabelSize.width
)
self.titleEdgeInsets = UIEdgeInsets(
top: 0.0,
left: -imageViewSize.width,
bottom: -(totalHeight - titleLabelSize.height),
right: 0.0
)
self.contentEdgeInsets = UIEdgeInsets(
top: 0.0,
left: 0.0,
bottom: titleLabelSize.height,
right: 0.0
)
}
}
//你创建了一个Btn,直接调用 Btn.centerVertically(设置间距),就会在Btn上面创建一个UIImageView和一个UILabel并且设置好了frame,只是在合适的地方设置图片和label内容即可,不合适了再在上面代码中调整frame布局