Ham Dong Kyun
Ham Dong Kyun

Reputation: 776

Custom UIVIew is not shown

I have created a simple UIView class that will show a label on runtime.

@IBDesignable
class CalendarDayView: UIView {

    var dayLabel = UILabel()

    @IBInspectable
    var day: Int {
        set {
            dayLabel.text = String(newValue)
        }
        get {
            return Int(dayLabel.text!)!
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareSubviews()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        prepareSubviews()
    }

    func prepareSubviews() {
        dayLabel.backgroundColor = UIColor.blue
        addSubview(dayLabel)
        dayLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor)
        dayLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor)
        dayLabel.widthAnchor.constraint(equalTo: self.widthAnchor)
        dayLabel.heightAnchor.constraint(equalTo: self.heightAnchor)
        setNeedsLayout()
    }
}

I have added a UIView on a simple view controller in the story board and set its width and height as 100. In the attribute inspector, the day value is set as 1.

I don't get to see the custom view background color (which should be blue) nor the label (which should show 1). Did I miss out something?

Upvotes: 1

Views: 1235

Answers (1)

BallpointBen
BallpointBen

Reputation: 13889

Wow, I've probably had this error myself 1000 times, can't believe I didn't recognize it at first glance (then again that's probably why I've had it 1000 times).

// .isActive = true
dayLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
dayLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
dayLabel.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
dayLabel.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true

Upvotes: 2

Related Questions