position: fixed; top: auto !important; margin-left: 112px;

What is UITableView?

Copied to clipboard..

UITableView is used to display the list of elements in the row. The best example to assume UITableView is "Contacts List in WhatsApp." Yes, the list of contacts we all see in WhatsApp App is created using UITableView.


Reusability of cells in UITableView

UITableView consists of a number of rows in vertical view and each row is called a cell. These cells are created in a reusable manner which means the cells which are visible on your phone screen are created first and when you scroll the screen, same cells will be used from memory instead of creating it every time. This is done using reuseIdentifier. We will explore this topic in below example in more depth.

In simple terms, Suppose you want to create a list of 1000 contacts in your app using UITableView. Then instead of creating a thousand rows each time "UITableView" provides a way to reuse the existing rows so that the rows which are visible on screen are created and when you scroll the UITableView same rows will be used again instead of new row creation.

Delegate and DataSource Methods

These are the delegate and datasource methods which help in creating TableView cells. numberOfRowsinsection tells how many rows we need in our table view. cellForRowAt method actually creates cells for us. heightForRowAt defines the height of row cell.


 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int ;
  
func numberOfSectionsInTableView(tableView: UITableView) -> Int 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat


//more methods which are used with UITableView Reference object.
.reloadData();

.reloadRows(at: [indexPath], with: .top)

UITableView Example

This example helps you to understand the basics of UITableView. Here,we will create a Codzify App which displays the list of tutorials available in codzify.com website.

Final Output :-


Getting Started

Open Xcode Goto File > New >Project >Single View Application > Enter Project Name (eg :- FirstProjectViewController) and Select Language as Swift> Done.

Now you can see a file on left navigation Menu of Xcode named, ViewController.swift

We will first start with AppDelegate.swift File. Copy and paste this code in didFinishLaunchingWithOptions method (the very first method you can see in Appdelegate.swift).


 import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
              
        window = UIWindow(frame: UIScreen.main.bounds)
        let mainController = ViewController() as UIViewController
        let navigationController = UINavigationController(rootViewController: mainController)
        navigationController.navigationBar.isTranslucent = false
        self.window?.rootViewController = navigationController
        self.window?.makeKeyAndVisible()
        
        return true
    }

AppDelegate is the file which is called first when your App Starts. This is the basic app so you might get only one controller file named as ViewController.swift in your XCode project. But in companies, there might be many ViewControllers for big projects. So to make our app aware that this is the ViewController I wanna call at the first launch of my app you have to specify it in your AppDelegate didFinishLaunchingApplications method. So in didFinishLaunchingApplications we told our code to begin with ViewController file.

UINavigationController is mostly you see in every App. This is a header with teal color as you see in Final Output Image. Word itself tells its meaning. It Controls all the navigation of the iOS App.


self.window?.rootViewController = navigationController

In this way, you can set Root View Controller of your app. In our case we want ViewController.swift file to be the first one to start with.

ViewController.swift file looks like this:

 import UIKit

 class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
    
    private let myArray: NSMutableArray = ["C","Objective-C","Swift"]
    private var myTableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.init(red: 245/255.0, green: 245/255.0, blue: 245/255.0, alpha: 1.0);
        
        self.navigationItem.title = "Programming Languages"
        
        self.navigationController?.navigationBar.barTintColor = UIColor.init(red: 0/255.0, green: 128/255.0, blue: 128/255.0, alpha: 1.0)
        self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
        self.navigationController?.navigationBar.tintColor = UIColor.white
        
        
        myTableView = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: self.view.frame.height - 60))
        myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        myTableView.dataSource = self
        myTableView.delegate = self
        myTableView.backgroundColor = UIColor.clear
        myTableView.separatorStyle = UITableViewCellSeparatorStyle.none
        self.view.addSubview(myTableView)

    }
    
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 0 // you should probably return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myArray.count
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        print("Num: \(indexPath.row)")
        print("Value: \(myArray[indexPath.row])")
        
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
     {
       let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath)
       
       cell.textLabel!.text = "\(myArray[indexPath.row])"
        
       return cell
    }
    
   func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
        return 60
    }
}

A short description of Example:

We have given a backgroundColor to NavigationBar with title Programming Languages and assigned text Color of title as White .

Here, viewDidLoad() method is called first. If you haven't seen the ViewControllers View Life Cycle, we prefer to have a look at this concept first. In this method, we initialized a UITableView .

myTableView = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: self.view.frame.height - 60))

Then, we registered a datasource and delegate methods of TableView.


myTableView.dataSource = self
myTableView.delegate = self

Then you have to register the forCellReuseIdentifier and give it same name which you use in cellForRowAtIndexPath method of UITableView.


myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

Last line adds tableViewTutorialsTitle as a subView inside view.

 self.view.addSubview(myTableView)

In numberOfRowsInSection we are going to use the count of elements in our NSMutableArray to tell the tableView how many rows to create:


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myArray.count
  }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath)
                cell.textLabel!.text = "\(myArray[indexPath.row])"
        
        return cell
    }

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
        return 60
}

This method is used to set the height of a row.



Previous Next Article







codzify.com


Largest collection of up-to-date tutorials to learn programming languages. We are focused on easy learning. Massive collection of interview questions one may need for preparation.

Social Profile


Linkedin
Twitter
Facebook

Copyright 2018. All rights reserved.