如果我有一个 subview Controller :
autoCompleteViewController.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
autoCompleteViewController.view.topAnchor.constraint(equalTo: view.topAnchor, constant: 0),
autoCompleteViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0),
autoCompleteViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0),
autoCompleteViewController.view.bottomAnchor.constraint(equalTo: googleMapViewController.view.topAnchor, constant: 0),
autoCompleteViewController.view.heightAnchor.constraint(equalToConstant: 44.0)
])
如何更改它的高度并更新 heightAnchor
?我试过这个:
autoCompleteViewController
.view
.heightAnchor
.constraint(equalToConstant: initialHeightAutoCompleteViewController + CGFloat(numberOfSuggestions * 45))
.isActive = true
但没有运气。我还尝试添加 layoutIfNeeded()
和其他一些类似的方法,但没有用。如何使用 anchor 更新 View 高度?
最佳答案
除@Mukesh 之外,答案只是更新约束:
var heightAnchor:NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
heightAnchor = autoCompleteViewController.view.heightAnchor.constraint(equalToConstant:44.0)
heightAnchor.isActive = true
}
func changeMyHeight(numberOfSuggestions: Int) {
heightAnchor.constant = 44.0 + CGFloat(numberOfSuggestions * 45)
}
注意事项:
- 您不能在类级别完全声明此变量,因为
autoCompleteViewController.view
尚未实例化。 - 您不能同时设置约束和设置
isActive = true
。我总是遇到构建错误。
关于ios - 如何更改已经具有高度 anchor 的 UIView 的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45144640/