Swift — How to implement tableView programmatically swift

ODENZA
1 min readJul 22, 2021

--

In this article, I would like to show you a basic how to implement tableView by programmatically without using storyboard in Swift5.

Step:1 Let’s create your project and setup navigationView in SceneDelegate.swift file

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {guard let windowScene = (scene as? UIWindowScene) else { return }
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UINavigationController(rootViewController: ViewController())window.makeKeyAndVisible()self.window = window}

Step: 2 Add subclass “UITableViewDataSource, UITableViewDelegate” and add code below.

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {private let cellId = "cellId"
let items = ["Ant", "Bird", "Cat", "Dog"]
private let tableView: UITableView = {
let table = UITableView()
table.translatesAutoresizingMaskIntoConstraints = false
return
table
}()
override func viewDidLoad() {super.viewDidLoad()navigationItem.title = "Animals"tableView.dataSource = selftableView.delegate = self
view.addSubview(tableView)
tableView.frame = view.bounds
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return items.count}func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)cell.textLabel?.text = items[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {print(indexPath.row)}}

This is source code: https://github.com/Odenza-lab/ImplementTableView

--

--

ODENZA
ODENZA

No responses yet