Swift - 展开并居中的 TextView

Swift - TextView that expands and stays in center

我正在努力实现我脑海中的一个想法,但我被卡住了..


我需要一个可以双向扩展的 TextView:widht-height。

具有最小和最大宽度以及最小高度。

即居中于父 (SCROLL) 视图的中间。

并且在视图的底部尾部有一个按钮 send

思路如下:

因此,如果用户在框中键入内容,那么它会向两个方向展开。但是它有一个最大宽度(所以它不会离开屏幕)但是高度没有限制:由于父滚动视图。


问题是当文本换行时,textView 的高度不会扩展。

代码:

func textViewDidChange(_ textView: UITextView) {
    self.adjustTextViewFrames(textView: textView)
}
func adjustTextViewFrames(textView : UITextView){

    var newSize = textView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))



    if newSize.width > self.view.bounds.width - 20 {
        newSize.width = self.view.bounds.width - (self.view.bounds.width/10)
    }

    messageBubbleTextViewWidthConstraint.constant = newSize.width
    messageBubbleTextViewHeightConstraint.constant = newSize.height

    UIView.animate(withDuration: 0.3) {
        self.view.layoutIfNeeded()
    }

}

试试这个:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // let's create our text view
        let textView = UITextView()
        textView.frame = CGRect(x: 0, y: 0, width: 200, height: 100)
        textView.backgroundColor = .lightGray
        textView.text = "Here is some default text that we want to show and it might be a couple of lines that are word wrapped"

        view.addSubview(textView)

        // use auto layout to set my textview frame...kinda
        textView.translatesAutoresizingMaskIntoConstraints = false
        [
            textView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
            textView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            textView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            textView.heightAnchor.constraint(equalToConstant: 50)
            ].forEach{ [=10=].isActive = true }

        textView.font = UIFont.preferredFont(forTextStyle: .headline)

        textView.delegate = self
        textView.isScrollEnabled = false

        textViewDidChange(textView)
    }

}

extension ViewController: UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {
        print(textView.text)
        let size = CGSize(width: view.frame.width, height: .infinity)
        let estimatedSize = textView.sizeThatFits(size)

        textView.constraints.forEach { (constraint) in
            if constraint.firstAttribute == .height {
                constraint.constant = estimatedSize.height
            }
        }
    }

}

感谢 Brian Voong 来自 Let's Build That App here link