ios - 将参数添加到 UILabel 初始值设定项

标签 ios swift 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)

中添加它

最佳答案

要在 swift 中覆盖 init() 方法,您应该使用关键字 convenience。 例如,您可以添加初始化程序:

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

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

}

注意 self.init(frame:frame) 语句,它通过调用默认初始化程序来初始化 UILabel

关于ios - 将参数添加到 UILabel 初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35583441/

相关文章:

swift - 对成员 'close()' 的引用不明确

objective-c - 解析查询包含非精确字符串

ios - UILabel sizeToFit 不适用于自动布局 ios6

objective-c - 用于 Web 查询的多个同时 NSConnections

ios - 问题在 Swift 中使用 prepareForSegue 方法传递自定义单元格的内容

ios - 为 BOOL 指针赋值时出现奇怪的警告问题

ios - 无法在 labelText 中提供动态值

ios - "Expected expression in Swift key path"使用扩展重构代码时出错

ios - 按钮之间的标签在哪里

ios - 在特定时间后更改 UILabel