我创建了一个简单的UIView类,它将在运行时显示标签。
@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()
}
}
我在故事板中的一个简单视图控制器上添加了一个UIView,并将其宽度和高度设置为100.在属性检查器中,日值设置为1.
我无法看到自定义视图背景颜色(应该是蓝色),也不会看到标签(应该显示1)。我错过了什么吗?
答案 0 :(得分:1)
// .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