守着一只汪
这是我发现导致高度正确更新的最小解决方案。似乎有两个关键组成部分:translatesAutoresizingMaskIntoConstraints设置为的视图false需要添加到视图层次结构中。高度约束的添加时间不得早于viewWillAppear。我仍然Unable to simultaneously satisfy constraints在日志中看到错误,但是无论如何看来工作正常。我还仍然看到一个跳跃,在该跳跃中,高度最初设置为默认值,然后再跳跃到设置值。我还没有找到解决这些问题的方法。import UIKitclass KeyboardViewController: UIInputViewController { var heightConstraint: NSLayoutConstraint! override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.inputView.addConstraint(self.heightConstraint) } override func viewDidLoad() { super.viewDidLoad() let dummyView = UILabel(frame:CGRectZero) dummyView.setTranslatesAutoresizingMaskIntoConstraints(false) self.view.addSubview(dummyView); let height : CGFloat = 400 self.heightConstraint = NSLayoutConstraint( item:self.inputView, attribute:.Height, relatedBy:.Equal, toItem:nil, attribute:.NotAnAttribute, multiplier:0.0, constant:height) }}Swift 4更新:import UIKitclass KeyboardViewController: UIInputViewController{ private weak var _heightConstraint: NSLayoutConstraint? override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard nil == _heightConstraint else { return } // We must add a subview with an `instrinsicContentSize` that uses autolayout to force the height constraint to be recognized. // let emptyView = UILabel(frame: .zero) emptyView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(emptyView); let heightConstraint = NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0.0, constant: 240) heightConstraint.priority = .required - 1 view.addConstraint(heightConstraint) _heightConstraint = heightConstraint }}