未熟学生エンジニアのブログ

TetsuFeの個人開発ブログ

TetsuFeはテツエフイー と読みます。FlutterやWeb周り全般、チーム開発について語るブログ

【iOS】tableViewで配列をリスト表示する

tableViewの使い方(リスト構造との連携編) tableView をstoryBoardにドラッグ

table view の設置 

1 ViewController.swiftにプロトコルを追加

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { }

Type ‘ViewController’ does not conform to protocol ‘UITableViewDataSource’とエラーが出る場合

http://mirai-stereo.net/2014/11/07/swift-does-not-conform-to-protocol-uitableviewdatasource/ この場合2つのメソッドをきちんと書け、ってエラー func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { }
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { }
を書けばOK

2 行数を返す関数を作る(引数:UITableView, numberOfRowsInSection section) -> Int

func tableView(tableView: UITableView, numberOfRowsInSection section : Int) -> Int { return 行数 }

3 セルの内容を設定する関数を作る(引数:UITableView, NSindexPath) -> UITableViewCell

func tableView(tableView : UITableView, cellForRowAtIndexPath indexPath : NSIndexPath) -> UITableViewCell { let arrayElement = arrray[indexPath.row] let cell = UITableViewCell(style: .Default, reuseIdentifier: "myCell") cell.textLabel?.text = arrayElement }

2,3の補足  配列要素をtableViewに表示させたい場合

//まず、配列arrayを定義 var array = Array() //セルの数を決める func tableView(tableView: UITableView, numberOfRowsInSection section : Int) -> Int { return array.count } //セルを作る関数3tableViewの引数のindexPathのrowメンバは、2のtableViewの返り値array.countの分だけ自動的に0からforループで回るので、rowメンバを配列の添え字に設定しておけば、セルがその分追加される。 func tableView(tableView : UITableView, cellForRowAtIndexPath indexPath : NSIndexPath) -> UITableViewCell { let arrayElement = arrray[indexPath.row] let cell = UITableViewCell(style: .Default, reuseIdentifier: "myCell") cell.textLabel?.text = arrayElement }

4 tableViewとdataSource・delegateをつなげる

storyboard上でtableViewをドラッグ、上の左から1番目のアイコンへ。 dataSource・dalefateを選択

これで配列の文字列がtableViewでリスト表示できました!