【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
4 tableViewとdataSource・delegateをつなげる
storyboard上でtableViewをドラッグ、上の左から1番目のアイコンへ。 dataSource・dalefateを選択
これで配列の文字列がtableViewでリスト表示できました!