我怎样才能写入以下代码使用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