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

时间:2015-10-25 03:36:46

标签: ios swift uiviewcontroller uilabel subclass

我的目标是在我的视图控制器中设置我的自定义textColor子类的UILabel。我有一个名为UILabel的{​​{1}}子类。以下是它的基础知识:

CircleLabel

}

如您所见,我实例化的每个CircleLabel默认为UIColor.whiteColor()的textColor属性,该属性正常工作。在我的视图控制器的viewDidLoad中,我想将CircleLabel设置为具有动态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 } 属性。所以像这样:

textColor

这不起作用,因为在class myViewController: UIViewController { @IBOutlet weak var myCustomLabel: CircleLabel! override func viewDidLoad() { super.viewDidLoad() myCustomLabel.textColor = UIColor.blackColor() } 子类的textColor方法中设置了drawRect。我可以在我的UILabel子类中实现什么(通过我的setProperties帮助方法或其他方式的辅助方法),这样我可以在视图控制器中设置自定义标签的CircleLabel

2 个答案:

答案 0 :(得分:23)

截图

在您的情况下,您不需要覆盖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.
    }

}

答案 1 :(得分:0)

1。快速自定义标签

    class CustomLabel: UILabel {

    @IBInspectable var topInset: CGFloat = 5.0
    @IBInspectable var bottomInset: CGFloat = 5.0
    @IBInspectable var leftInset: CGFloat = 7.0
    @IBInspectable var rightInset: CGFloat = 7.0

    override func drawText(in rect: CGRect) {
        let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
        super.drawText(in: rect.inset(by: insets))
    }

    override var intrinsicContentSize: CGSize {
        let size = super.intrinsicContentSize
        return CGSize(width: size.width + leftInset + rightInset,
                      height: size.height + topInset + bottomInset)
    }
}