问题描述
我的目标是在我的视图控制器中设置我的自定义 UILabel
子类的 textColor
。我有一个名为 CircleLabel
的 UILabel
子类。以下是它的基础知识:
My goal is to set the textColor
of my custom UILabel
subclass in my view controller. I have a UILabel
subclass named CircleLabel
. Here are the basics of it:
class CircleLabel: UILabel {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override func drawRect(rect: CGRect) {
self.layer.cornerRadius = self.bounds.width/2
self.clipsToBounds = true
super.drawRect(rect)
}
override func drawTextInRect(rect: CGRect) {
self.textColor = UIColor.whiteColor()
super.drawTextInRect(rect)
}
func setProperties(borderWidth: Float, borderColor: UIColor) {
self.layer.borderWidth = CGFloat(borderWidth)
self.layer.borderColor = borderColor.CGColor
}
}
如您所见,我实例化的每个CircleLabel默认为UIColor.whiteColor()的textColor属性,它可以正常工作。在我的视图控制器的viewDidLoad中,我想将CircleLabel设置为具有动态 textColor
属性。所以类似这样:
As you can see, every CircleLabel I instantiate is defaulted to a textColor property of UIColor.whiteColor(), which works properly. In my view controller's viewDidLoad, I want to set my CircleLabel to have a dynamic textColor
property. So something like this:
class myViewController: UIViewController {
@IBOutlet weak var myCustomLabel: CircleLabel!
override func viewDidLoad() {
super.viewDidLoad()
myCustomLabel.textColor = UIColor.blackColor()
}
这不起作用,因为在中设置了
textColor
drawRect UILabel
子类的方法。我可以在我的 CircleLabel
子类中实现什么(通过我的setProperties辅助方法或其他方式的辅助方法),这将允许我设置 textColor
我的视图控制器中的自定义标签?
That doesn't work because textColor
is set in the drawRect
method of the UILabel
subclass. What can I implement in my CircleLabel
subclass (via a helper method like my setProperties helper method or some other way) that would allow me to set the textColor
of my custom label in my view controller?
推荐答案
屏幕截图
你在你的情况下,不需要覆盖 drawRect
,只需创建这样的类
You do not need to override drawRect
in your case,just create the class like this
class CircleLabel: UILabel {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
func commonInit(){
self.layer.cornerRadius = self.bounds.width/2
self.clipsToBounds = true
self.textColor = UIColor.whiteColor()
self.setProperties(1.0, borderColor:UIColor.blackColor())
}
func setProperties(borderWidth: Float, borderColor: UIColor) {
self.layer.borderWidth = CGFloat(borderWidth)
self.layer.borderColor = borderColor.CGColor
}
}
然后
class ViewController: UIViewController {
@IBOutlet weak var myCustomLabel: CircleLabel!
override func viewDidLoad() {
super.viewDidLoad()
myCustomLabel.textColor = UIColor.blackColor()
// Do any additional setup after loading the view, typically from a nib.
}
}
这篇关于UILabel子类使用自定义颜色初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!