1
votes

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?

1
Did you set the width and height of dayLabel? - BallpointBen
Shouldn't the auto layout constraints take care of that? - Ham Dong Kyun
However, you may need to set dayLabel.translatesAutoresizingMaskIntoConstraints = false - BallpointBen
Also, are you explicitly setting the frame of the CalendarDayView? Try putting in a breakpoint and printing out the frame after it has been initialized and added to whatever superview you added it to. - creeperspeak
That does not resolve why my custom view background color is not shown. - Ham Dong Kyun

1 Answers

2
votes

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