gpt4 book ai didi

ios - View 约束——适合一个 subview

转载 作者:搜寻专家 更新时间:2023-10-31 21:52:45 24 4
gpt4 key购买 nike

我正在向 View 添加一个 subview ,我希望它填充 View 的高度和宽度。我在约束方面遇到困难。任何帮助表示赞赏。这是我目前拥有的:

    self.view.addSubview(self.mainView)

var leftSideConstraint = NSLayoutConstraint(item: self.mainView, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 0.0)
var bottomConstraint = NSLayoutConstraint(item: self.mainView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1.0, constant: 0.0)
var widthConstraint = NSLayoutConstraint(item: self.mainView, attribute: .Width, relatedBy: .Equal, toItem: self.view, attribute: .Width, multiplier: 1.0, constant: 0.0)
var heightConstraint = NSLayoutConstraint(item: self.mainView, attribute: .Height, relatedBy: .Equal, toItem: self.view, attribute: .Height, multiplier: 1.0, constant: 0.0)
self.view.addConstraints([leftSideConstraint, bottomConstraint, widthConstraint, heightConstraint])

最佳答案

swift 5

这是使用 UIView 扩展的优雅方式

extension UIView {
func addConstrained(subview: UIView) {
addSubview(subview)
subview.translatesAutoresizingMaskIntoConstraints = false
subview.topAnchor.constraint(equalTo: topAnchor).isActive = true
subview.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
subview.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
subview.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
}

然后你在任何你需要的地方添加一个 subview

yourContainerView.addConstrained(subview: yourSubview)

关于ios - View 约束——适合一个 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25701790/

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