iOS UITABLEVIEW tutorial using SWIFT

Mobile Application Development

iOS UITABLEVIEW tutorial using SWIFT

In most of the application you will need to use UITABLEVIEW. UITABLEVIEW is a list of data we are displaying.
The main Objective of this blog is to learn simple table view with Delegate and Datasource method in swift programming language in iOS.
Let’s Start with all Steps we are following:
STEP 1: Create New Project
Create new XCode Projects

STEP 2: Name the project
Here I am using SimpleTableView, and save this project in appropriate folder

STEP 3: Add tableView in your view controller
Drag and drop Table View in our view controller in main.storyboard
Select the tableview, in Attribute Inspector, set the prototype cells 1 as indicated below. STEP 4: Set the cell
Select Cell, in attribute inspector, Change the identifier name as cell-name, I am using ‘cell’ here.

STEP 5: Set Delegate and Datasource connection with tableview
Select the tableview and drag and drop by right click of mouse to the view controller, and set datasource and delegate method on.

STEP 6: Initialize the array to display data in list.
Now declare the array globally which is storing the list which we are going to display in UITableView.
Here I am using ‘array’ which is storing 10 numbers.

var array : [String]?

Initialize the array with data

array = [“1”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”]

STEP 7: Set Delegate and Datasource method in ViewController
Now add the UITableViewDelegate and UITableViewDataSource with ViewController, So your class ViewController will look like

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
……..
}
Add delegate method of UITABLEVIEW
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

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

}

At last your code will look like:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    // Declare array to store list of data
    var array : [String]?
    override func viewDidLoad() {
        super.viewDidLoad()
        // Initialize array
        array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
    }
    // MARK: UITABLEVIEW Delegate and Datasource Method
    // This function will return the number of item
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array?.count ?? 0
    }
    // This function will return the cell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        cell?.textLabel?.text = array?[indexPath.row]
        return cell ?? UITableViewCell()
    }
}

That’s it.
Build the code & Run it. You will get your list.

 

error:
×