Swift

【Swift】UITableViewControllerの使い方

UITableViewControllerを使ってUITableViewを表示する方法を解説します。

UITableViewControllerを使う

「UITableView」を画面に表示するには普通の「ViewController」に「UITableView」を配置するか、「UITableViewController」を使う方法があると思いますが、今回は簡単で利用しやすい「UITableViewController」を使います。

「ViewController」に「UITableView」を配置する方法はこちら

UITableViewControllerを追加する

まず、「ViewController」を削除して、「UITableViewController」を追加します。

「Table View Controller」 をドラッグして画面に配置します。

配置したら「Is Initial View Controller」 にチェックを入れます。

次に、「ViewController」のファイルを削除して「TableViewController」のファイルを作成します。

「Main.storyboard」のあたりで右クリックして、「New File…」を選択します。

「Cocoa Touch Class」を選択します。

Class名を入力し(ここでは「TableViewController」にします)、「Subclass of」は必ず「UITableViewController」にして「Next」を押して「Create」してください。

次に 「Main.storyboard」で「TableView」を選択し「Custom Class」のClassを追加したファイルのクラス名と同じものにします。

最後に「TableViewの中のセル」を選択し、「Identifier」を任意の値にします。

ここでは「reuseIdentifier」にします。

コードを書く

先ほど追加したTableViewController.swiftにコードを書いていきます。

今回は13行目に追加した配列を表示していきます。

//
//  TableViewController.swift
//  UITableView
//
//  Created by user on 2021/06/20.
//

import UIKit

class TableViewController: UITableViewController {
    
    //配列を追加
    var languages: [String] = ["Swift", "Java", "Ruby", "Javascript", "PHP"]

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

    // MARK: - Table view data source
    
    //セクションの数(1つの場合はなくても大丈夫です)
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    //TableViewに表示させるセルの数
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return languages.count
    }
    
    //コメントアウトを解除することでそのまま使えます。UITableViewに表示させるセルを返します
    //dequeueReusableCellのwithIdentifierはセルのIdentifierと同じものにします
    //indexPath.rowは0からセルの数までの連番です
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
        cell.textLabel?.text = languages[indexPath.row]
        return cell
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

これで「TableView」が表示されるようになりました。