一浊服、簡介
在iOS中,UIButton只能顯示一個圖片在左狂巢,文字在右的按鈕撑毛,如下圖:
普通按鈕
但有時候,我們需要一個圖片在上方唧领,文字在下方的按鈕藻雌,并且能在Storyboard或者Xib中顯示自定義按鈕雌续,如下圖:
自定義實時渲染按鈕
二、實現(xiàn)
直接上代碼:
import UIKit
@IBDesignable // 給該類加上@IBDesignable關(guān)鍵字胯杭,則可在xib中渲染
class CustomButton: UIButton {
// @IBInspectable:給xib提供設(shè)置屬性驯杜,可以xib中看到此屬性
@IBInspectable var borderColor:UIColor?{
didSet{
self.layer.borderColor = borderColor?.cgColor
}
}
// @IBInspectable:給xib提供設(shè)置屬性,可以xib中看到此屬性
@IBInspectable var borderWidth:CGFloat = 0{
didSet{
self.layer.borderWidth = borderWidth
}
}
// @IBInspectable:給xib提供設(shè)置屬性做个,可以xib中看到此屬性
@IBInspectable var cornerRadius:CGFloat = 0{
didSet{
self.layer.cornerRadius = cornerRadius
self.layer.masksToBounds = true
}
}
override func layoutSubviews() {
super.layoutSubviews()
guard let titleLabel = titleLabel, let imageView = imageView else { return }
imageView.frame.origin.y = 10
imageView.center.x = frame.width * 0.5
titleLabel.sizeToFit()
titleLabel.center.x = frame.width * 0.5
titleLabel.frame.origin.y = imageView.frame.maxY + 5
}
}
最后鸽心,別忘記更改Custom Class
為自定義類
,如圖: