LoginSignup
11
12

More than 5 years have passed since last update.

UITextViewにて入力文字列に応じた高さの伸縮をコーディングなしで実装する

Last updated at Posted at 2017-03-13

先日投稿のあった以下の記事を拝見して
「UITextView自体の伸縮だけだったらもう少し簡単にできたような・・・?」と思ってたところ
最近実装する機会があったのでメモ。
http://qiita.com/KikurageChan/items/4e1a467858eb2323e009

上記記事と同様に、背景に設定してるUIViewと一緒に伸び縮みさせる感じ。
可変テキストボックス.gif

実装

Storyboard上のAutoLayoutの設定のみで対応。
ただし、高さが変更された際に併せて他のこともしたい場合は
UITextViewDelegateのメソッドでガリガリすることが必須。

その1. 背景用のUIViewを放り込んで、幅とY座標を確定させる

例:
スクリーンショット 2017-03-10 13.31.02.jpg

その2. UITextViewを上記UIView内の子要素として放り込んで、幅とY座標を確定させる

例:
スクリーンショット 2017-03-10 13.34.09.jpg

その3. UITextViewの高さを決める(Greater Than or Equalを選択)

例:
スクリーンショット 2017-03-10 13.35.21.jpg

その4. 親のUIViewとUITextViewの高さを連動させる

例:
スクリーンショット 2017-03-10 13.35.52.jpg

その5. UITextViewのScrollViewの設定にて、Scrolling EnabledとBouncesのチェックを外す

例:
スクリーンショット 2017-03-10 13.36.48.jpg

その6. 5まででレイアウトのエラーが警告になるので、Update Framesをして完成

例:
スクリーンショット 2017-03-10 13.37.37.jpg

1〜6までで以下の設定がされる。
スクリーンショット 2017-03-10 13.45.39.jpg

11
12
1

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
11
12