【IOSアプリ開発:xcode】UITableViewを使用する

今回はTableViewを使用します。

TableViewとは下に示した図のように用意した文章などをそれぞれの行に並べて示すことができるものです。

 

f:id:yokoblog_b:20200212214841p:plain

 

 

では早速説明していきます。

 

 

1)Main.storyboard

まず初めにmain.storyboardを編集します。

object選択画面からTable Viewを選択し、画面にドラッグ&ドロップします。

そして全画面に表示されるように引き伸ばします。(別に引き伸ばさなくても良いが)

 

f:id:yokoblog_b:20200212215727p:plain

 

 

その後、Table View CellをTable Viewの中に入るようにドラッグ&ドロップすることで次の画面のようになります。

正しく出来ていれば左のような構図になります。

f:id:yokoblog_b:20200212221001p:plain

 

Objectの設置はここまでで終了です。

次の作業として、設置したObjectをView Controllerと関連付けます。

このための作業として、Table Viewの上で右クリックし、画像のように黒いタブが出てきますので、"dataSource"と"delegate"の◯とスマホ画面の上にある黄色いView Controllerをそれぞれつなげます。

f:id:yokoblog_b:20200212222539p:plain

 

 最後にTable View Cellにタグ付け?みたいなことをしておきます。

Table View Cellを選択した時のidentiferに"tableCell"と名前をつけておきます。

この名前は自分でわかりやすい名前に変更しても構いません。

これであとはプログラムを書くだけになります。

f:id:yokoblog_b:20200212223908p:plain

 

 

 

 

2)ViewController.swift 

 まず今回記述したプログラムを示しておきます。

import UIKit

 

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    

 

    var Countrylist = ["日本","アメリカ","ロシア"]

 

    override func viewDidLoad() {

        super.viewDidLoad()

    }

    

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

    }

    

    //テーブルの行数を指定するメソッド

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return Countrylist.count

    }

    

    //セルの中身を設定するメソッド

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        //セルを取得

        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)

        

        //セルに値を設定

        cell.textLabel!.text = Countrylist[indexPath.row]

        return cell

    }

 

}

 

 

では説明します。

1:まずTable ViewのDatasourceとDelegateを使用するためにクラスに継承させます。

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate

 

2:Table View Cellに表示させる項目についての配列を作成する

var Countrylist = ["日本","アメリカ","ロシア"] 

 

3:テーブルの行数を指定するメソッド

今回はCountrylistの項目の数を返しています。

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return Countrylist.count

    }

 

4:セルの中身を設定するメソッド

//セルの中身を設定するメソッド

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        //セルを取得

        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)

        

        //セルに値を設定

        cell.textLabel!.text = Countrylist[indexPath.row]

        return cell

    }

 

 

 

以上の設定により実行することで最初に示した画面のようにCoutrylistの項目がTableに表示されるようになります。