下面是我的自定义UILabel的代码:
class RoleLabel: UILabel {
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
self.setup()
}
override init(frame:CGRect) {
super.init(frame:frame)
self.setup()
}
override func awakeFromNib() {
super.awakeFromNib()
self.setup()
}
func setup(){
numberOfLines = 1
font = UIFont(name:"HelveticaNeue-Bold", size: 16.0)
sizeToFit()
frame = CGRectMake(frame.minX, frame.minY, frame.width + 40, frame.height+5)
backgroundColor = UIColor.blackColor()
textColor = UIColor.whiteColor()
layer.cornerRadius = 5
layer.shadowOffset = CGSize(width: 2, height: 2)
layer.shadowOpacity = 0.7
layer.shadowRadius = 2
drawTextInRect(frame)
let btn = UIButton()
btn.setTitle("X", forState: .Normal)
btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
btn.frame = CGRectMake(frame.width-20, 1, 20, 23)
addSubview(btn)
}
let topInset = CGFloat(0), bottomInset = CGFloat(0), leftInset = CGFloat(3), rightInset = CGFloat(0)
override func drawTextInRect(rect: CGRect) {
let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
}
但是,由于标签根据文本调整大小,我需要将文本作为参数传递给初始化器。
有没有办法添加这种自定义参数?override init(frame:CGRect)
中不允许添加
1条答案
按热度按时间1szpjjfi1#
要覆盖swift中的
init()
方法,你应该使用关键字convenience
。例如,你可以添加初始化器:请注意
self.init(frame:frame)
语句,它通过调用默认初始化器来初始化UILabel
。