Tuesday, 29 November 2016

How to create UITableview in Swift - Tutorial

UITableView in Swift Tutorial

Introduction to UITableView in Swift:

UITableView is the basic control used in mobile apps. In this tutorial, we will learn how to create UITableView in swift language. All teh delgates for the tableview are same only syntax changes is there in swift language Let us start creating UITableView in swift.

Implementation of code for UITableView:

Create a single view application template and press next button

Select Single view application template


Name your project "UITableView-Swift" and select your development language as Swift language

Select Development language as Swift language 

Chose the location to save your project files and press create.

Now as we successfully created our project, open Main.storyboard and drag UITableView to the view. Add constraints (assuming that you know auto-layout). You can change your view's screen size from Attributed inspector as shown in below image

Change Screen Size of your view to iPhone 4- inch


 Open ViewController.swift file, create IBOutlet for our UITableView  and declare our cellIdentifier.


    @IBOutlet var tblList : UITableView?
    let cellIdentifier = "cellIdentifier"


Open Main.storyboard file and connect IBOutlet created in previous step with UITableView. Also connect UIItableView's delegate and datsource outlets with ViewController.

Connecting our UITableViews delegate and datasource Outlets to ViewController

 Open ViewController.swift file, here we will implement our UITableView delegates and data source
methods


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5;
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        
        var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier)
        if cell == nil {
            cell = UITableViewCell.init(style:UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier)
        }
        cell?.textLabel?.text = "row";
        return cell!;

    }


Run your app and you will see UITableView showing text inside rows. You can modify the code as per your needs.

Download Code for UITableView in swift: UitableView-Swift Source Code

Where to go from here:

In this tutorial you learned, how to create UITableView in swift language. I hope you enjoyed this post on How To create UITableview in Swift - Tutorial. If you have any questions, please feel free to comment.


No comments:
Write comments