はじめに
苦手意識のあるUIKitを克服しよう企画!
これからUIKitの記事も投稿します!
今回はコードのみで最小実装のTableViewを作成してみたいと思います。
まずStoryboardを消します。
これは以前書いたので飛ばします。
完成サンプル
実装
import UIKit
class ViewController: UIViewController {
let avengers: [String] = ["ソー", "ドクター・ストレンジ", "アイアンマン", "キャプテン・マーベル", "スパイダーマン", "ハルク", "キャプテン・アメリカ"]
private let tableView: UITableView = {
let view = UITableView(frame: .zero, style: .grouped)
view.translatesAutoresizingMaskIntoConstraints = false
view.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
private func setup() {
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
avengers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
var content = cell.defaultContentConfiguration()
content.text = avengers[indexPath.row]
cell.contentConfiguration = content
return cell
}
}
おわり
SwiftUIばっかやってると忘れるので基本形を記録しておきます笑