【Swift】tableViewでセルを表示する

 

完成画面

 

f:id:nekokichi_yos2:20181007224631p:plain

 

必要なプロセス

 

プロセス - StoryBoard編

 

  1. tableView、tableViewCellを配置
  2. tableViewのIdentifierを設定
  3. tableViewにOutletで紐付け
  4. tableViewCellの上にUILabelを配置
  5. UILabelのtagを1に設定

 

1.

f:id:nekokichi_yos2:20181007224626p:plain

 

2.

f:id:nekokichi_yos2:20181007224635p:plain

 

5.

f:id:nekokichi_yos2:20181007224642p:plain

 

プロセス - ViewContoller編

 

  1. UITableViewDelegate,UITableViewDataSourceを記述
  2. viewDidLoad()でdelegate,datasourceを宣言..?
  3. 表示したいテキストを配列で用意(今回はtextという名前の配列)
  4. セルの表示に必要な4つの関数を用意(numberOfSections、numberOfRowsInSection、cellForRowAt、heightForRowAt)

 

1.

f:id:nekokichi_yos2:20181007224621p:plain

 

 

numberOfSections:セルを分類するカテゴリの数

               今回は分類しないので return 1

numberOfRowsInSection:セルの数

               text配列の要素数を指定

cellForRowAt:セルを生成に関わる関数

               StoryBoardで設定したセルのIdentifierを記述

               //で設定したtagでUILabelを生成(今回は1)

heightForRowAt:1つのセルの高さ

               お好みで

 

ソースコード

 

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    
    let text = ["one","two","three","four","five","six"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.delegate = self
        tableView.dataSource = self
        
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return text.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
        let textLabel = cell.viewWithTag(1) as! UILabel
        textLabel.text = text[indexPath.row]
        
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 62
    }

}

 

※補足:セル上にテキストを表示させる方法について

 

セルにテキストを表示る場合、

 

  • 直接代入:cell.textLabel?.text = “文字列”
  • UILabel:cell.viewWithTag() as! UILabel
  • カスタムセル

 

の3通り。

 

今回は、セルの上に配置したUILabelで、セルにテキストを表示させた。

 

注意点としては、セルの配置したUILabelを紐付けすることができないこと。

 

ImageViewはかろうじて配置できるが、それ以外はおそらく不可能。

 

なので、tagを指定し、cell.viewWithTagによって、tagで指定したUI部品を変数で生成する必要がある。