UILabel subclass initialize with custom color

后端 未结 2 1465
时光取名叫无心
时光取名叫无心 2021-02-04 13:37

My goal is to set the textColor of my custom UILabel subclass in my view controller. I have a UILabel subclass named CircleLabel

2条回答
  •  迷失自我
    2021-02-04 14:14

    Screenshot

    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
        }
    }
    

    Then

    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.
        }
    
    }
    

提交回复
热议问题