Swift - 扩展并保持在中心

时间:2018-06-02 21:42:45

标签: swift textview constraints

我正在努力完成一个我想到的想法,但我被卡住了..

我需要一个以两种方式扩展的TextView:widht-height。

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

它位于父(SCROLL)视图的中间位置。

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

以下是这个想法:

enter image description here

因此,如果用户在框中键入,则它会向两个方向展开。但它有一个最大宽度(因此它不会离屏)但高度不受限制:由于父卷轴视图。

问题是当文本分成新行时,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()
    }

}

1 个答案:

答案 0 :(得分:1)

试试这个:

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{ $0.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
            }
        }
    }

}

来自让我们在这里构建应用程序的link

,来自Brian Voong