我的目标是在我的视图控制器中设置我的自定义UILabel子类的textColor.我有一个名为CircleLabel的UILabel子类.以下是它的基础知识:
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属性.所以这样的事情:
class myViewController: UIViewController { @IBOutlet weak var myCustomLabel: CircleLabel! override func viewDidLoad() { super.viewDidLoad() myCustomLabel.textColor = UIColor.blackColor() }
这不起作用,因为textColor是在UILabel子类的drawRect方法中设置的.我可以在我的CircleLabel子类中实现什么(通过帮助器方法,比如我的setProperties帮助器方法或其他方式),这样我可以在视图控制器中设置自定义标签的textColor?
解决方法
截图
在您的情况下,您不需要覆盖drawRect,只需创建这样的类
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. } }