joethemow
joethemow

Reputation: 1773

Why is the label not being added to the view?

I am trying to add a label to the UIView. I am seeing the view, but I am not seeing the label. What am I missing?

var StLabel: UILabel = {
            let label = UILabel()
            label.font = UIFont(name: "Arial-Regular", size: 20)
            label.textColor = UIColor.black
            label.sizeToFit()
            return label
    }()

    init(frame: CGRect, text: String) {
        super.init(frame: frame)
        self.frame = CGRect(x: 0, y: 0, width: 300, height: 50)
        self.layer.cornerRadius = 10
        self.layer.masksToBounds = true
        self.backgroundColor = UIColor.white
        StLabel.text = text
        self.addSubview(StLabel)
    }

Upvotes: 0

Views: 41

Answers (1)

rmaddy
rmaddy

Reputation: 318804

You are calling sizeToFit() on the label before its text is set so the label's frame ends up with a 0 size.

Add a call to StLabel.sizeToFit() after the line StLabel.text = text.

Upvotes: 1

Related Questions