LoginSignup
88
69

More than 5 years have passed since last update.

UITableView上に可変するUITextViewを作る

Posted at

やりたいこと

こういうのを作る。
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

88
69
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
88
69