ios – UILabel子类使用自定义颜色初始化

前端之家收集整理的这篇文章主要介绍了ios – UILabel子类使用自定义颜色初始化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的目标是在我的视图控制器中设置我的自定义UILabel子类的textColor.我有一个名为CircleLabel的UILabel子类.以下是它的基础知识:
  1. class CircleLabel: UILabel {
  2.  
  3. required init(coder aDecoder: NSCoder) {
  4. super.init(coder: aDecoder)!
  5. }
  6.  
  7. override init(frame: CGRect) {
  8. super.init(frame: frame)
  9. }
  10.  
  11. override func drawRect(rect: CGRect) {
  12. self.layer.cornerRadius = self.bounds.width/2
  13. self.clipsToBounds = true
  14. super.drawRect(rect)
  15. }
  16.  
  17. override func drawTextInRect(rect: CGRect) {
  18. self.textColor = UIColor.whiteColor()
  19. super.drawTextInRect(rect)
  20. }
  21.  
  22. func setProperties(borderWidth: Float,borderColor: UIColor) {
  23. self.layer.borderWidth = CGFloat(borderWidth)
  24. self.layer.borderColor = borderColor.CGColor
  25. }

}

如您所见,我实例化的每个CircleLabel都默认为UIColor.whiteColor()的textColor属性,该属性正常工作.在我的视图控制器的viewDidLoad中,我想将CircleLabel设置为具有动态textColor属性.所以这样的事情:

  1. class myViewController: UIViewController {
  2. @IBOutlet weak var myCustomLabel: CircleLabel!
  3.  
  4. override func viewDidLoad() {
  5. super.viewDidLoad()
  6. myCustomLabel.textColor = UIColor.blackColor()
  7. }

这不起作用,因为textColor是在UILabel子类的drawRect方法中设置的.我可以在我的CircleLabel子类中实现什么(通过帮助器方法,比如我的setProperties帮助器方法或其他方式),这样我可以在视图控制器中设置自定义标签的textColor?

解决方法

截图

在您的情况下,您不需要覆盖drawRect,只需创建这样的类

  1. class CircleLabel: UILabel {
  2.  
  3. required init(coder aDecoder: NSCoder) {
  4. super.init(coder: aDecoder)!
  5. self.commonInit()
  6.  
  7. }
  8.  
  9. override init(frame: CGRect) {
  10. super.init(frame: frame)
  11. self.commonInit()
  12. }
  13. func commonInit(){
  14. self.layer.cornerRadius = self.bounds.width/2
  15. self.clipsToBounds = true
  16. self.textColor = UIColor.whiteColor()
  17. self.setProperties(1.0,borderColor:UIColor.blackColor())
  18. }
  19. func setProperties(borderWidth: Float,borderColor: UIColor) {
  20. self.layer.borderWidth = CGFloat(borderWidth)
  21. self.layer.borderColor = borderColor.CGColor
  22. }
  23. }

然后

  1. class ViewController: UIViewController {
  2.  
  3. @IBOutlet weak var myCustomLabel: CircleLabel!
  4. override func viewDidLoad() {
  5. super.viewDidLoad()
  6. myCustomLabel.textColor = UIColor.blackColor()
  7. // Do any additional setup after loading the view,typically from a nib.
  8. }
  9.  
  10. }

猜你在找的iOS相关文章