In this tutorial I will show you how to create a basic UITableView using code only, no Storyboard, no xib, just Code.
Lets dive in…
- Open Xcode and create a new Single View App project, give it a name TableView, click next, save it somewhere and click Create.
- Delete the ViewController.swift in the Xcode Navigator.
- Click on the Project name in the Navigator, go to the General Tab, under Deployment Info, delete the “Main” Storybaord, it should stay empty.
- Create a new Swift file and name it TableViewExample
- Add the following code to the TableViewExample.swift file you just created.
import UIKitclass TableViewExample: UITableViewController {
let cellId = “cellId”
override func viewDidLoad() {
super.viewDidLoad()
setupTableView() }
func setupTableView(){
//Registers a class for use in creating new table cells.
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
}
}
Open AppDelegate.swift, in the didFinishLaunchingWithOptions method add the following code.
window = UIWindow()
window?.makeKeyAndVisible()
window?.rootViewController = TableViewExample()
Now lets add those UITableView Delegate Methods.
open TableViewExample.swift and at the end of the file add the following extension.
extension TableViewExample {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
cell.textLabel?.text = "Hello, World"
return cell}}
Build and run.
Other Articles:
Diffable Data Sources & Compositional Layouts part 1
Diffable Data Sources & Compositional Layouts part 2