はじめに
TableViewでタプルを使ってみます。
タプルの基本的な解説は省きます。
GitHub
実装
以下のように、Cocoa Touch Class
でSubclass
をUITableViewController
にしてください。
そして、以下のように書き換えます。
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()
}
}
MyTableViewController
はUITableViewController
を継承しているので、このなかに直接書くことができます。
var models: [(String, (() -> Void))] = []
ここでタプルを使っていますね。
Main.storyboard
はNavigationController
を追加し、ViewController
にUIButton
を一つ追加してください。
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)
}
}
先ほどのMyTableViewController
のmodels
にタプルの配列を渡しています。
おわりに
おわりです。