自定义UIVIew未显示

时间:2017-03-01 23:08:24

标签: swift uiview

我创建了一个简单的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)。我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

哇,我自己可能已经有1000次犯这个错误了,不敢相信我乍看之下就没认出来了(那可能就是为什么我已经1000次了)。

// .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