如何在UIView子类中使用NSLayoutConstraints(或锚定)编写以下代码?
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的纵横比。如果你需要更多的信息,请告诉我。
请用迅捷3,谢谢。
最佳答案
检查以下代码:
let view = UIView(frame: CGRectZero)
view.setTranslatesAutoresizingMaskIntoConstraints(false)
super.init(frame: frame)
let viewsDict = ["view": view]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[view]-0-|", options: .allZeros, metrics: nil, views: viewsDict))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[view]-0-|", options: .allZeros, metrics: nil, views: viewsDict))
addSubview(view)
关于ios - 自动布局而不是自动调整大小,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40802240/