4
2

More than 1 year has passed since last update.

【Swift】コードのみでTableViewを実装する

Posted at

はじめに

苦手意識のあるUIKitを克服しよう企画!
これからUIKitの記事も投稿します!
今回はコードのみで最小実装のTableViewを作成してみたいと思います。

まずStoryboardを消します。
これは以前書いたので飛ばします。

完成サンプル

simulator_screenshot_D6F38B34-27C3-4D07-BA91-A4B6BDD9DB55.png

実装

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ばっかやってると忘れるので基本形を記録しておきます笑

4
2
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
4
2