課題
以下の記事を参考にし、UITextViewの高さをデフォルト3行にし、入力内容に合わせて高さを変え、5行以上はスクロールで表示することはできたのですが、ボタン押下後に入力していたtextを空にした場合、入力していた文字の高さがtextViewに残ってしまいます。
ボタン押下後はデフォルト(3行分)のtextViewの高さに戻し、上記と同じ動作を繰り返せるようにするにはどうしたら良いでしょうか?
import UIKit
class ViewController:UIViewController {
@IBOutlet weak var testView: UITextView!
@IBOutlet weak var textViewHeight: NSLayoutConstraint!
@IBOutlet weak var viewHeight: NSLayoutConstraint!
var currentTextViewHeight: CGFloat = 80
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.testView.delegate = self
}
@IBAction func tapButton(_ sender: Any) {
testView.text = ""
textViewHeight.constant = 80
}
}
extension ViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
let contentHeight = self.testView.contentSize.height
if 80.0 <= contentHeight && contentHeight <= 100.0 {
self.testView.translatesAutoresizingMaskIntoConstraints = true
self.testView.sizeToFit()
self.testView.isScrollEnabled = false
let resizedHeight = self.testView.frame.size.height
self.textViewHeight.constant = resizedHeight
self.testView.frame = CGRect(x: 60, y: 30, width: self.view.frame.width - 120, height: resizedHeight)
if resizedHeight > currentTextViewHeight {
let addingHeight = resizedHeight - currentTextViewHeight
self.viewHeight.constant += addingHeight
currentTextViewHeight = resizedHeight
} else if resizedHeight < currentTextViewHeight {
let subtractingHeight = currentTextViewHeight - resizedHeight
self.viewHeight.constant -= subtractingHeight
currentTextViewHeight = resizedHeight
}
} else {
self.testView.isScrollEnabled = true
self.textViewHeight.constant = currentTextViewHeight
self.testView.frame = CGRect(x: 60, y: 30, width: self.view.frame.width - 120, height: currentTextViewHeight)
}
}
}
ボタンタップのアクション内に textViewHeight.constant = 80
を書いたのですが高さが残ったままになってしまうのでデフォルトの高さに戻したいです。
デフォルトの高さ | 入力文字数で高さ可変 | ボタン押下後 |
---|---|---|
![]() |
![]() |
![]() |
viewの設定(height=120) | textViewの設定(height=80) |
---|---|
![]() |
![]() |
補足
textViewのheight=80、textViewのsuperViewのheight=120でstoryBoardでは設定しています。