ios - 如何更改已经具有高度 anchor 的 UIView 的高度?

标签 ios swift nslayoutconstraint

如果我有一个 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/

相关文章:

ios - 上传到 VPP 商业商店灰显

ios - Xcode 4.5 背景图像 iPhone 4、4s、5

ios - UIKeyCommand 操作未被调用

ios - 具有不同 UI Swift 的行,并重用不同 View Controller 中的任何单元格以避免重复编码

iOS 11 : "Unable to simultaneously satisfy constraints"

ios - 如何调整自定义 UITableViewCell 的大小以适应内容?

ios - Xcode 7 - 代码覆盖率数据生成失败

swift - 为什么在这种情况下非可选函数可以返回 nil?

ios - 如何向我的 UICollectionView 添加一个额外的静态单元格?

ios - UITextView 替代方案