我正在以编程方式创建我的 UI,我想让我的 UITextfield
topAnchor
以其包含的 UIView
的高度为基础,但是它不起作用。
我的 UITextfield
位于 UIView
内,我希望它的 topAnchor
是 UIView
高度的 0.15因此 - containerView.frame.size.height * 0.15
但它的值似乎没有上升。所有这些都在 UIView
子类中完成,并在 ViewController
let containerView: UIView
containerView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(containerView)
NSLayoutConstraint.activate([
containerView.centerXAnchor.constraint(equalTo: self.centerXAnchor),
containerView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.9),
containerView.topAnchor.constraint(equalTo: stepTitleLabel.bottomAnchor, constant: 50),
containerView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.65)
])
let userTextField: UITextField
userTextField?.tag = 1
userTextField?.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(userTextField)
userTextField.setNeedsLayout()
print("containerView.frame.size.height * 0.15:\(containerView.frame.size.height * 0.15)")
NSLayoutConstraint.activate([
(userTextField.centerXAnchor.constraint(equalTo: containerView.centerXAnchor))!,
(userTextField.widthAnchor.constraint(equalTo: containerView.widthAnchor, multiplier: 0.8))!,
userTextField.topAnchor.constraint(equalTo: containerView.topAnchor, constant: containerView.frame.size.height * 0.15),
userTextField.heightAnchor.constraint(equalToConstant: 40)
])
我希望我的 UITextField
的 topAnchor 在容器 View 的高度为 0.15 时在所有设备上看起来都相似,但我得到的是 0
最佳答案
不要混合使用 NSLayoutConstraint
和 frame
。这些框架是静态的,当您将它们用于约束中的常量
时不会更新。因此,当 Auto Layout 使用其他约束来更新 containerView
的高度时,查看 containerView
框架高度的约束将基于创建约束时 containerView
的高度(可能是 0
),而不是 Auto Layout 使用约束来建立containerView
的高度。
相反,您想将 userTextField
的 top
放在 containerView
的 bottom
上,并使用 乘数
。不幸的是,你不能用布局 anchor 来做到这一点,你必须使用 NSLayoutContraint
来创建它:
替换:
userTextField.topAnchor.constraint(equalTo: containerView.topAnchor,
constant: containerView.frame.size.height * 0.15)
与:
NSLayoutConstraint(item: userTextField, attribute: .top, relatedBy: .equal,
toItem: containerView, attribute: .bottom, multiplier: 0.15, constant: 0)
关于ios - 布局约束不适用于 view.frame.size.height,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56020632/