我怎樣才能寫入以下代碼使用NSLayoutConstraints(或錨)在UIView子類?自動佈局代替autoresizingMask
func commonInit() {
aView = UIView()
aView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
addSubview(aView)
}
override func layoutSubviews() {
super.layoutSubviews()
let smallerSide = min(bounds.width, bounds.height)
aView.bounds = CGRect(x: 0.0, y: 0.0, width: smallerSide, height: smallerSide)
aView.center = CGPoint(x: bounds.midX, y: bounds.midY)
}
一個目的是避免使用layoutSubviews()
。 此外,aView
必須保持1:1的寬高比。 如果您需要更多信息,請告訴我。
PS:請讓我們用swift3,謝謝。
感謝您的答案,但它有一些問題:必須在添加約束之前將視圖添加爲子視圖。我的目標是不要用另一種觀點來填補子類 - 但要在中心有一個正方形,邊長比爲1:1。 –
@這只是填充超級視圖。不是OP想要的。 – BangOperator