Swift 按鈕 圖片在上 文字在下 :tw-2b06: :tw-2b07:
簡介
怎麼讓按鈕圖片在上? swift按鈕圖片文字都是左右,想要上下佈局就要客製化,不管事圖片在下還是圖片在上、文字在下還是文字在下,Button都要做擴充處理。
宣告UIButton
10為圖片文字間距
lineBtn.centerImageAndButton(10, imageOnTop: true)
擴充UIButton
extension UIButton {
func centerImageAndButton(_ gap: CGFloat, imageOnTop: Bool) {
guard let imageView = self.currentImage,
let titleLabel = self.titleLabel?.text else { return }
let sign: CGFloat = imageOnTop ? 1 : -1
self.titleEdgeInsets = UIEdgeInsets(top: (imageView.size.height + gap) * sign, left: -imageView.size.width, bottom: 0, right: 0);
let titleSize = titleLabel.size(withAttributes:[NSAttributedString.Key.font: self.titleLabel!.font!])
self.imageEdgeInsets = UIEdgeInsets(top: -(titleSize.height + gap) * sign, left: 0, bottom: 0, right: -titleSize.width)
}
}