以下のサイトを参考に通常のCellとカスタムセルで例を作ってみました、これでCellの高さが自動で計算されると思います。
UITableViewCellの高さを自動で計算する: UITableViewAutomaticDimension
※参考URL
デフォルトのUITableViewCellを使用した方法
swift
1
2import UIKit
3
4class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
5
6 @IBOutlet weak var myTableView: UITableView!
7
8 override func viewDidLoad() {
9 super.viewDidLoad()
10
11 myTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
12
13 myTableView.estimatedRowHeight = 20
14 myTableView.rowHeight = UITableViewAutomaticDimension
15 }
16
17 // Data Array
18 var dataArray = ["複数行文字1、複数行文字1、複数行文字1、複数行文字1、複数行文字1、複数行文字1、複数行文字1","複数行文字2、複数行文字2、複数行文字2、複数行文字2","文字3","文字4","文字5","文字6","文字7"]
19
20 // Row Count
21 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
22 return dataArray.count
23 }
24
25 // Generate Cell
26 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
27 let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
28 cell.textLabel?.numberOfLines = 0
29 cell.textLabel?.text = dataArray[indexPath.row]
30 return cell
31 }
32}
カスタムセルを使用した方法
swift
1import UIKit
2
3class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
4 // Storyboardに乗せたUITableView
5 @IBOutlet weak var myTableView: UITableView!
6
7 override func viewDidLoad() {
8 super.viewDidLoad()
9
10 myTableView.estimatedRowHeight = 20
11 myTableView.rowHeight = UITableViewAutomaticDimension
12 }
13
14 // Data Array
15 var dataArray = ["複数行文字1、複数行文字1、複数行文字1、複数行文字1、複数行文字1、複数行文字1、複数行文字1","複数行文字2、複数行文字2、複数行文字2、複数行文字2","文字3","文字4","文字5","文字6","文字7"]
16
17 // Row Count
18 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
19 return dataArray.count
20 }
21
22 // Generate Cell
23 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
24 let cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! CustomCell
25 cell.label.text = dataArray[indexPath.row]
26 return cell
27 }
28}
29
30// CustomCell
31class CustomCell: UITableViewCell {
32 // StoryboardのCustomCellにラベルを一つ乗せ紐つける
33 @IBOutlet weak var label: UILabel!
34}
結果
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/06/28 23:04
2016/06/28 23:19 編集
2016/06/30 03:12