0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】TableViewでタプルを使う

Posted at

はじめに

TableViewでタプルを使ってみます。
タプルの基本的な解説は省きます。

GitHub

実装

以下のように、Cocoa Touch ClassSubclassUITableViewControllerにしてください。
スクリーンショット 2021-04-01 9.22.11.png

そして、以下のように書き換えます。

MyTableViewController
import UIKit

final class MyTableViewController: UITableViewController {
    
    var models: [(String, (() -> Void))] = []
    private let cellId = "cell"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return models.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
        cell.textLabel?.text = models[indexPath.row].0
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        models[indexPath.row].1()
    }
    
}

MyTableViewControllerUITableViewControllerを継承しているので、このなかに直接書くことができます。
var models: [(String, (() -> Void))] = []ここでタプルを使っていますね。

Main.storyboardNavigationControllerを追加し、ViewControllerUIButtonを一つ追加してください。
スクリーンショット 2021-04-01 9.25.22.png

ViewControllerの実装は以下のようになります。

ViewController
import UIKit

final class ViewController: UIViewController {
    
    @IBAction func buttonOneDidTapped(_ sender: Any) {
        let vc = MyTableViewController()
        vc.models = [
            ("swift", { print("swift") }),
            ("ruby", { print("ruby") }),
            ("php", { print("php") }),
            ("python", { print("python") }),
            ("java", { print("java") }),
        ]
        navigationController?.pushViewController(vc, animated: true)
    }
    
}

先ほどのMyTableViewControllermodelsにタプルの配列を渡しています。

おわりに

おわりです。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?