一、简介
在iOS中,UIButton只能显示一个图片在左,文字在右的按钮,如下图:
普通按钮
但有时候,我们需要一个图片在上方,文字在下方的按钮,并且能在Storyboard或者Xib中显示自定义按钮,如下图:
自定义实时渲染按钮
二、实现
直接上代码:
import UIKit
@IBDesignable // 给该类加上@IBDesignable关键字,则可在xib中渲染
class CustomButton: UIButton {
// @IBInspectable:给xib提供设置属性,可以xib中看到此属性
@IBInspectable var borderColor:UIColor?{
didSet{
self.layer.borderColor = borderColor?.cgColor
}
}
// @IBInspectable:给xib提供设置属性,可以xib中看到此属性
@IBInspectable var borderWidth:CGFloat = 0{
didSet{
self.layer.borderWidth = borderWidth
}
}
// @IBInspectable:给xib提供设置属性,可以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
为自定义类
,如图: