gpt4 book ai didi

ios - 自动布局而不是 autoresizingMask

转载 作者:行者123 更新时间:2023-11-28 09:29:34 25 4
gpt4 key购买 nike

如何在 UIView 子类使用 NSLayoutConstraints(或 anchor )编写以下代码?

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,谢谢。

最佳答案

检查下面的代码:

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 - 自动布局而不是 autoresizingMask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40802240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com