gpt4 book ai didi

swift - 以编程方式将约束添加到 Storyboard 上的现有 View

转载 作者:行者123 更新时间:2023-11-30 10:06:12 24 4
gpt4 key购买 nike

我发现当以编程方式键入 Storyboard上的现有 View 时,约束没有实现纠正。这是我所拥有的:

class ViewController: UIViewController {

@IBOutlet weak var textField2: UITextField! {
didSet {
textField2.delegate = self
}
}

func viewDidLoad() {
super.viewDidLoad()

let superview = self.view

let textField1 = UITextField()
textField1.backgroundColor = UIColor.greenColor()
textField1.placeholder = "test text field"
view.addSubview(textField1)
textField1.translatesAutoresizingMaskIntoConstraints = false
superview.addConstraint(NSLayoutConstraint(item: textField1, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: superview.frame.width * 0.50))
superview.addConstraint(NSLayoutConstraint(item: textField1, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: superview.frame.height * 0.05))
superview.addConstraint(NSLayoutConstraint(item: textField1, attribute: .CenterX, relatedBy: .Equal, toItem: superview, attribute: .CenterX, multiplier: 1, constant: 0))
superview.addConstraint(NSLayoutConstraint(item: textField1, attribute: .CenterY, relatedBy: .Equal, toItem: superview, attribute: .CenterY, multiplier: 1, constant: 0))

textField2.translatesAutoresizingMaskIntoConstraints = false
superview.addConstraint(NSLayoutConstraint(item: textField2, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: superview.frame.width * 0.50))
superview.addConstraint(NSLayoutConstraint(item: textField2, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: superview.frame.height * 0.05))
superview.addConstraint(NSLayoutConstraint(item: textField2, attribute: .CenterX, relatedBy: .Equal, toItem: superview, attribute: .CenterX, multiplier: 1, constant: 0))
superview.addConstraint(NSLayoutConstraint(item: textField2, attribute: .CenterY, relatedBy: .Equal, toItem: superview, attribute: .CenterY, multiplier: 1, constant: 0))

}
}

textField1 工作完美。它被添加到 View 的中心。但是,我拖放到 Storyboard 上的 textField2 偏离了中心。为什么会发生这种情况?

谢谢

最佳答案

问题是,如果 View 来自 Storyboard,例如您的 textField2,它已经有约束。说 textField2.translatesAutoresizingMaskIntoConstraints = false 并不能神奇地解决这个问题。您还需要以某种方式掌握这些约束,并在代码中应用您自己的约束之前删除它们。这可能很难做到,而没有这样做,这就是为什么你的观点行为不当。在这个阶段,您最好遵循以下简单规则:

  • 如果 View 来自 Storyboard,则仅在 Storyboard中设置其约束

  • 但是如果 View 是用代码创建的,现在您可以说 translatesAutoresizingMaskIntoConstraints = false 并在代码中设置其约束

关于swift - 以编程方式将约束添加到 Storyboard 上的现有 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35821226/

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