UITableViewでUITableViewCellの高さを自動で可変する
今回はUILabelとUITextViewを使用した場合にUITableViewCellの高さを自動で可変する方法を書きます。UITableViewは予め設定し終わった状態と過程して話を進めます。
StoryBoard上の設定は以下のようにmarginをセットしてます。
画像はUILabelですが、UITextViewも同じようにします。
UILabelを使用するときは設定でLinesを0にしてください。
UITextViewを使用するときは設定でScrolling Enabledのチェックを外してください。
そして以下のコードを追記します。
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension }
estimatedHeightForRowAtIndexPathは予めUITableViewCellの高さを指定してやることで実際に表示した際に負荷を軽減してくれます。
heightForRowAtIndexPathは実際のUITableViewCellの高さを取得します。
今回は返り値にUITableViewAutomaticDimensionというUITableViewCellの高さを自動で取得してくれる値を書きます。
ちなみにネット上で色々コードが転がっていたので、それぞれ試してみました。
//OK tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100 //OK tableView.rowHeight = UITableViewAutomaticDimension func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } //OK これが同じ所に書けるし、一番いいのでは? func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } //NG 何故・・・estimatedRowHeightにはUITableViewAutomaticDimensionを直に設定することが出来ない tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = UITableViewAutomaticDimension