LoginSignup
26
18

More than 5 years have passed since last update.

[iOS] UITextViewの高さを内容によって動的に変更する

Last updated at Posted at 2017-05-15

今回のやりたいこと

UITextViewの内容は、Web経由で取得する。
内容の長さは様々である。
それに合わせて、UITextViewの高さを動的に変更したい。

方法

まずはUITextViewDelegateのtextViewDidChange()でtextの内容が変わったら呼び出されるので、その時に高さの設定する方法を試した。

extension ViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        var frame = textView.frame
        frame.size.height = textView.contentSize.height
        textView.frame = frame
    }
}

これだと、UITextView.textに文章を設定しても呼び出されなかった。
(本来なら、呼び出されるはずなんだけど。。。)

次にUITextView.sizeThatFits()で高さを動的に取得する方法で試した。

let height = textView.sizeThatFits(CGSize(width: textView.frame.size.width, height: CGFloat.greatestFiniteMagnitude)).height
textView.heightAnchor.constraint(equalToConstant: height).isActive = true

これでうまく動的に高さの変更ができた。

めでたし、めでたし。

26
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
18