gpt4 book ai didi

ios - 使用 TopLayoutGuide 的制图约束

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

我有一个 View ,我希望它看起来像这样:

|---------------|
| | <- navBar
|---------------|
| | <- topView
|---------------|
| |
| |
| |
|---------------|

我想要的只是将 topView.top 粘贴到 navBar.bottom。我决定使用制图并实现以下代码(尝试坚持使用 MVC ofc):

在我的 UIViewController 子类中:

override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()

aView?.topLayoutGuide = self.topLayoutGuide // where aView is my subclass of UIView, inserted in loadView method
}

在我的 UIView 子类中:

var topLayoutGuide: UILayoutSupport?

override func updateConstraints() {
var constraint = NSLayoutConstraint?()
layout(topView) { (topView) in
constraint = topView.top == topView.superview!.top
}
topView.superview!.removeConstraint(constraint!)

layout(topView) { topView in
topView.top == topView.superview!.top + (self.topLayoutGuide?.length ?? 0)
topView.height == 67
topView.left == topView.superview!.left
topView.width == topView.superview!.width
}

super.updateConstraints()
}

问题是我收到以下日志,但我不知道如何解决:

Unable to simultaneously satisfy constraints.
[...]
(
"<NSLayoutConstraint:0x7fe6a64e4800 V:|-(64)-[UIView:0x7fe6a6505d80] (Names: '|':MyApp.MyView:0x7fe6a360d4c0 )>",
"<NSLayoutConstraint:0x7fe6a3538a80 V:|-(0)-[UIView:0x7fe6a6505d80] (Names: '|':MyApp.MyView:0x7fe6a360d4c0 )>"
)

看来我需要一些帮助。如何正确地做到这一点?我不想在 UIViewController 中实现约束,也不想使用 Storyboards

感谢您的帮助!

最佳答案

一个解决方案:创建对特定 NSLayoutConstraint 的引用,并更新其常量:

var topLayoutConstraint: NSLayoutConstraint!

override func updateConstraints() {
layout(topView) { topView in
topLayoutConstraint = topView.top == topView.superview!.top
topView.height == 67
topView.left == topView.superview!.left
topView.width == topView.superview!.width
}

super.updateConstraints()
}

...然后,您可以像这样调整 NSLayoutConstraint 的常量:

topLayoutConstraint.constant = 50

剩下的唯一问题是 - 何时更新 topLayoutConstraint?一种解决方案是创建一个协议(protocol),MyViewInterface:

protocol MyViewInterface: class {
var topLayoutGuideLength: CGFloat { get set }
}

然后,在我们的 UIView 中,当 topLayoutGuideLength 属性发生变化时,我们调整 NSLayoutConstraintconstant >:

public class MyView: UIView, MyViewInterface {
public var topLayoutGuideLength: CGFloat = 0 {
didSet {
topLayoutConstraint.constant = topLayoutGuideLength
}
}
}

最后,在我们的 UIViewController(我们的 topLayoutGuide 所在的地方):

public class myViewController: UIViewController {

private var myView: MyView

// ...

public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()

myView.topLayoutGuideLength = topLayoutGuide.length
}
}

结果呢?每当在我们的 UIViewController 上触发 viewDidLayoutSubviews() 时,我们的 myViewtopLayoutGuideLength 属性就会更新,这会触发更改 topLayoutConstraintconstant

关于ios - 使用 TopLayoutGuide 的制图约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30997463/

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