在 Swift 3 中更新通过 NSLayout 设置的 UITextView 大小

Update an UITextView size that is set via NSLayout in Swift 3

我的 UIViewController 中有一个变量与设置 UITextView 高度的约束相关联:
var textViewHeight: Int!

这是约束条件:
self.view.addConstraintsWithFormat(format: "V:|-74-[v0(\(textViewHeight!))]", views: self.textView)

我使用这个扩展:

extension UIView
{
    func addConstraintsWithFormat(format: String, views: UIView...)
    {
        var viewDict = [String: AnyObject]()
        for (index, view) in views.enumerated()
        {
            view.translatesAutoresizingMaskIntoConstraints = false
            let key = "v\(index)"
            viewDict[key] = view
        }
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewDict))
    }
}

我已经设置了一个在键盘出现时触发的通知。 它被正确触发(我有一个 print 并且它总是正确触发)并且执行的函数包括以下代码:

if let keyboardSize = sender.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? CGRect {
        print(keyboardSize.height)
        self.textViewHeight = Int(self.view.frame.height-keyboardSize.height-100)
        self.view.updateConstraints()
}

键盘的高度打印正确,但文本视图的高度没有改变.....
提前致谢!

如果变量值(在本例中 textViewHeight)稍后更改,则使用可视化格式简单地设置一次约束将不会在以后更新约束。因此,您必须通过代码实际设置约束,稍后可以在 textViewHeight 值更改时对其进行修改。

以下是您需要的更改:

1: 添加一个变量来保存对您稍后要修改的约束的引用。

var heightConstraint:NSLayoutConstraint!

2:单独为文本视图创建约束,而不是使用视觉格式 (self.view.addConstraintsWithFormat(format: "V:|-74-[v0(\(textViewHeight!))]", views: self.textView))

// Add vertical constraints individually
let top = NSLayoutConstraint(item:textView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem:topLayoutGuide, attribute: NSLayoutAttribute.bottom, multiplier:1.0, constant:74.0)
heightConstraint = NSLayoutConstraint(item:textView, attribute:NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem:nil, attribute:NSLayoutAttribute.notAnAttribute, multiplier:1.0, constant:textViewHeight)
view.addConstraint(top)
view.addConstraint(heightConstraint)

3:您最好将 textViewHeight 更改为 CGFloat,因为您将在那里处理的所有值都是 CGFloat 值而不是 Int

4:在你得到键盘通知的地方,在你计算textViewHeight之后,添加下面一行:

self.heightConstraint.constant = textViewHeight

这应该可以解决问题,因为现在 textViewHeight 发生变化时,约束也会更新 :)