18

我已经花了几天时间解决这个问题。

我有一个inputAccessoryView由一个UIView包含一个textView和两个按钮组成的。的行为与inputAccessoryView预期的一样,并且在除一种情况外的所有情况下都可以正常工作。

当 textView 的高度增加时,我试图将高度增加inputAccessoryView相同的量。当我重新定义 in 的高度时,inputAccessoryViewtextViewDidChange键盘inputAccessoryView上方而不是向上增加高度。

我尝试了 SO 的许多不同建议,但没有任何效果。我想这是自动添加NSLayoutConstraint的,inputAccessoryView但我不知道如何在 swift 和 iOS 8.3 中更改该值。

func textViewDidChange(textView: UITextView) {

    var contentSize = messageTextView.sizeThatFits(CGSizeMake(messageTextView.frame.size.width, CGFloat.max))

    inputAccessoryView.frame.size.height = contentSize.height + 16

}

添加

inputAccessoryView.setTranslatesAutoresizingMaskIntoConstraints(true)

对上面的代码有帮助,并且 inputAccessoryView 的高度正确地向上增加,但是我无法同时满足多个约束的约束,并且很难识别违规者。此外,我还得到了一个奇怪的效果,即 textView 在每第二个新行实例的下方创建额外的空间。

谢谢。

4

2 回答 2

53

要使输入附件视图垂直增长,您只需设置它autoresizingMask = .flexibleHeight,计算它intrinsicContentSize,然后让框架完成其余的工作。

编码:

class InputAccessoryView: UIView, UITextViewDelegate {

    let textView = UITextView()

    override init(frame: CGRect) {
        super.init(frame: frame)

        // This is required to make the view grow vertically
        self.autoresizingMask = UIView.AutoresizingMask.flexibleHeight

        // Setup textView as needed
        self.addSubview(self.textView)
        self.textView.translatesAutoresizingMaskIntoConstraints = false
        self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[textView]|", options: [], metrics: nil, views: ["textView": self.textView]))
        self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[textView]|", options: [], metrics: nil, views: ["textView": self.textView]))

        self.textView.delegate = self

        // Disabling textView scrolling prevents some undesired effects,
        // like incorrect contentOffset when adding new line,
        // and makes the textView behave similar to Apple's Messages app
        self.textView.isScrollEnabled = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override var intrinsicContentSize: CGSize {
        // Calculate intrinsicContentSize that will fit all the text
        let textSize = self.textView.sizeThatFits(CGSize(width: self.textView.bounds.width, height: CGFloat.greatestFiniteMagnitude))
        return CGSize(width: self.bounds.width, height: textSize.height)
    }

    // MARK: UITextViewDelegate

    func textViewDidChange(_ textView: UITextView) {
        // Re-calculate intrinsicContentSize when text changes
        self.invalidateIntrinsicContentSize()
    }

}
于 2015-09-18T09:08:23.183 回答
3

快进到 2020 年,您只需执行以下操作,其他一切都与 maxkonovalov 的答案相同

override var intrinsicContentSize: CGSize {
    return .zero
}

// MARK: UITextViewDelegate

func textViewDidChange(_ textView: UITextView) {
    sizeToFit()
}
于 2020-03-14T23:33:52.207 回答