Skip to content

Instantly share code, notes, and snippets.

@sigidhanafi
Last active April 19, 2022 13:51
Show Gist options
  • Save sigidhanafi/55509df1aa84ab8bf5565ebb045c91d4 to your computer and use it in GitHub Desktop.
Save sigidhanafi/55509df1aa84ab8bf5565ebb045c91d4 to your computer and use it in GitHub Desktop.
//
// ViewController.swift
// GettingStartedUITableView
//
// Created by Sigit on 13/11/20.
//
import UIKit
class ViewController: UIViewController {
// create property tableview
private let tableView = UITableView()
// STEP 3.1 Populating data
private let data: [String] = ["First Data", "Second Data"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = .white
// call function to setup view / tableview
self.setupView()
}
private func setupView() {
// STEP 3.2 conform the UITableViewDataSource
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellIdentifier")
// add tableview to VC view
view.addSubview(tableView)
// setting up constrains
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
}
}
// STEP 3.3 comform to tableview datasource
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath)
cell.backgroundColor = UIColor.white
cell.textLabel?.text = data[indexPath.row]
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment