2016-02-23 37 views
0

这是我自定义的UILabel代码:加入的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

要覆盖在swift中的init()方法,您应该使用关键字convenience。 举个例子,你可以添加初始化:

convenience init(frame:frame, text:String) { 

    self.init(frame:frame) 
    self.text = text 

} 

请注意self.init(frame:frame)声明,通过调用默认初始值初始化UILabel

+0

on self.init(frame:frame)它表示:“缺少参数文本的参数”@ tx2 – dpstart

+0

您是否将此初始化程序粘贴到您描述的类上? – tx2

+0

我已经按照你的方式编写了它,它说:“缺少参数文本的参数”,在行上:'self.init(frame:frame)' – dpstart