Skip to content

Display items in a table with UITableView(Swift4.2)

   

UITableView's class hierarchy

NSObject ↑ UIResponder ↑ UIView ↑ UIScrollView ↑ UITableView

AppleDeveloperリファレンスUITableView

alt

import UIKit
class TableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// tableview instance
private var tableView: UITableView!
// Array to display tableview
private var items: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
items = ["Apple", "Water melon", "Peach", "Cherry", "Grapes", "pear"]
// initialize tableview
tableView = UITableView()
// set delegate
tableView.delegate = self
tableView.dataSource = self
// set tableview size
tableView.frame = view.frame
// set tableview
tableView.register(UITableViewCell.self, forCellReuseIdentifier: NSStringFromClass(UITableViewCell.self))
view.addSubview(tableView)
}
// MARK: tableview delegate methods
// set the number of rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
// set tableview rows
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(UITableViewCell.self))! as UITableViewCell
cell.textLabel?.text = self.items[indexPath.row]
return cell
}
// called when tableview cell was tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("\(indexPath.row) cell was selected")
}
}

  1. Screen transition in NavigationController(Swift4.2)
  2. Switching the Root of NavigationController(Swift4.2)
  3. Selecting an image with ImagePickerController(Swift4.2)
  4. Function(Swift4.2)
  5. Array(Swift4.2)
  6. Print(Swift4.2)
  7. Search the contents of UITableView with UISearchBar(Swift4)