How To Create UITableView programatically in Swift 4

This Swift 4 code example will demonstrate how to create UITableView programatically in Swift 4.



The full code of the UITableView is below.
//
//  ViewController.swift
//  DemoProgam
//
//  Created by KIRIT MODI.
//  Copyright © 2018 KIRIT MODI. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var myTableView: UITableView  =   UITableView()
    var itemsToLoad: [String] = ["Kirit", "Modi"]

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        myTableView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        myTableView.dataSource = self
        myTableView.delegate = self
        myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        self.view.addSubview(myTableView)
    }

    // TableView delegate and Datasource.

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return itemsToLoad.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = itemsToLoad[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("User selected table row \(indexPath.row) and item \(itemsToLoad[indexPath.row])")
    }

}


Output :


Thanks.

How To Create UITableView programatically in Swift 4 How To Create UITableView programatically in Swift 4 Reviewed by KIRIT MODI on 09:18:00 Rating: 5

No comments:

Powered by Blogger.