Как динамически изменить ограничения textViews при наборе текста? - PullRequest
0 голосов
/ 25 апреля 2020

Я знаю этот вопрос, который многие задавали раньше, но я не могу заставить любое решение работать на меня. У меня есть этот UITextView, который я делаю программно с ограничениями, которые я также делаю программно. Моя цель - заставить textView увеличить свою высоту, когда текст внутри занимает слишком много места. Я не могу заставить эту работу работать, потому что ограничения уже установлены, или, по крайней мере, я думаю, что это проблема. Следующий код показывает, как я создаю textView, а также то, что я пытался сделать, чтобы он расширялся до сих пор

import UIKit

class ViewController: UIViewController, UITextViewDelegate {

var textView = UITextView()

var textViewHeight:NSLayoutConstraint?

var tempHeight:CGFloat = 0

override func viewDidLoad() {
    super.viewDidLoad()

    textView.translatesAutoresizingMaskIntoConstraints = false
    textView.layer.borderWidth = 1.5;
    textView.layer.cornerRadius = 5
    textView.layer.borderColor = UIColor(red:0.27, green:0.27, blue:0.27, alpha:1.00).cgColor;
    self.textView.delegate = self
    textViewHeight = textView.heightAnchor.constraint(equalTo: textView.widthAnchor, multiplier: 0.5)
    textView.isScrollEnabled = false
    self.view.addSubview(textView)


    let margineGuide = self.view.layoutMarginsGuide

    NSLayoutConstraint.activate([textView.leadingAnchor.constraint(equalTo: margineGuide.leadingAnchor, constant: 16),
    textView.trailingAnchor.constraint(equalTo: margineGuide.trailingAnchor, constant: -16),
    textView.topAnchor.constraint(equalTo: margineGuide.topAnchor, constant: 20),
    textViewHeight!])
    tempHeight = (self.view.frame.width * 0.5) - 32
}



func textViewDidChange(_ thisTextView: UITextView) {
    if (thisTextView == textView) {
        textView.sizeToFit()
        let tempHeight2 = textView.frame.height
        print(tempHeight2)
        print(tempHeight)
        if (tempHeight < tempHeight2) {
            textViewHeight = textView.heightAnchor.constraint(equalToConstant: tempHeight2)
            self.view.updateConstraints()
        } else {
            textViewHeight = textView.heightAnchor.constraint(equalTo: textView.widthAnchor, multiplier: 0.5)
        }
    } else {

    }

}


}

Надеюсь, вы сможете помочь:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...