Ham Dong Kyun Ham Dong Kyun -4 years ago 101
Swift Question

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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download