我在我的 superView 中创建了 2 个按钮,现在我想更改 @IBOutlet weak var bottomLayOut: NSLayoutConstraint!
取决于用户角色。
示例是:如果用户是代理角色而不是教师角色,我想将 NSLayoutConstraint
的第二项从 Teacher Entry .bottom 更新到 AgentEntry button's bottom 。
更新:
通过将 translatesAutoresizingMaskIntoConstraints
设置为 true 来解决这个问题:
例如:teacherBtn.translatesAutoresizingMaskIntoConstraints = true
除此之外,我们可以同时使用约束和代码来更改 teacherBtn 的框架
最佳答案
我可以想到两种方法来做到这一点:
- 以编程方式设置约束。创建一个包含按钮当前约束的属性,然后您可以按照以下方式做一些事情(免责声明:用 Chrome 编写,可能包含拼写错误,适当编辑):
` 如果让约束 = self.buttonConstraints { NSLayoutConstraint.deactivate(约束)
let views: [String : UIView] = ["Agent" : self.agentButton, "Teacher" : self.teacherButton]
let newConstraints: [NSLayoutConstraint] = {
switch role {
case .teacherAndAgent:
self.teacherButton.isHidden = false
self.agentButton.isHidden = false
return NSLayoutConstraint.constraints(withVisualFormat: "V:[agent]-[teacher]-|", metrics: nil, views: views)
case .teacherOnly:
// you get the idea
case .agentOnly:
// ditto
}
}()
NSLayoutConstraint.activate(newConstraints)
self.buttonConstraints = newConstraints`
- 不过,使用 UIStackView 来保存按钮可能更简单。至少在当前的 macOS 上,NSStackView 会根据隐藏的 View 自动调整布局;如果 iOS 上的 UIStackView 以相同的方式运行,它可能会为您完成很多工作,而无需手动处理布局约束。
关于ios - 如何更新 StoryBoard 中的 NSLayoutConstraint?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45929779/