Help us understand the problem. What is going on with this article?

UITableView上に可変するUITextViewを作る

More than 3 years have passed since last update.

やりたいこと

こういうのを作る。
c.gif

方法

  1. Storyboard上でtableViewのcellにtextViewを配置
  2. textViewに Auto Layout の制約を設定

    • textViewの上下左右のスペースに対して制約を設ける Screen Shot 2015-11-28 at 11.16.16 AM.png
  3. textViewのプロパティ Scrolling Enabled のチェックを外す
    Screen Shot 2015-11-28 at 11.16.16 AM 2.png

  4. textViewが自動でcellの高さを調整するように設定

    override func viewDidLoad() {
        super.viewDidLoad()
    
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 10000
    
        // ~~~
    }
    

    ここで注意!
    estimatedRowHeight を十分大きな値にしておかないと、textViewのサイズが画面を超えた状態でテキスト入力した際にスクロールが上下にバインバインと意図しない動きする。

  5. テキストが入力される度にtextViewの高さを調整

    • tableViewの beginUpdates()endUpdates() でcellが更新される
    // MARK: - TextViewDelegate
    
    func textViewDidChange(textView: UITextView) {
        tableView.beginUpdates()
        tableView.endUpdates()
    }
    

環境

Xcode 7.1
Swift 2.1
iOS 8以上で確認

参考

http://www.howlin-interactive.com/2013/01/creating-a-self-sizing-uitextview-within-a-uitableviewcell-in-ios-6/
http://stackoverflow.com/questions/29314535/uitableview-beginupdate-endupdate-causing-scroll-to-top

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした