gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 01:12:26 25 4
gpt4 key购买 nike

这是我的自定义 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com