Latest Posts

Sorry, no posts matched your criteria.

Stay in Touch With Us

Odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore.

Email
magazine@example.com

Phone
+32 458 623 874

Addresse
302 2nd St
Brooklyn, NY 11215, USA
40.674386 – 73.984783

Follow us on social

The Gadget Book

How To Create a Basic Table View in Xcode

In this Tutorial you will learn how to create a basic Table View in Xcode.

Start by creating a new Xcode Project, select “Single View App” and name it whatever you like.

Add a TableView Object to your ViewController, jump into the attributes inspector and also add one “prototype cell”. Select the cell and give it an identifier in the attributes inspector ,call this whatever you like but make sure you name this something meaningful as you will need it later.

Table View Xcode swift 4.0

We need to add the UITableViewDataSource protocol and also the UITableViewDelegate to the view controller class.

Create an IBOutlet to your Swift file for your table view, I am going to add a array of names so my table view can show that data.

 var names = ["Jack","Jill","Bob","Bill","Dee","Alex"].

In the ViewDidLoad method make sure you set the table view delegate and datasource.

 tableView.delegate = self
 tableView.dataSource = self

Xcode will give an error but do not worry, you need to add a few methods. Just below the ViewDidLoad method add the cellForRowAtIndexPath method and also the numberOfRowsInSection, this method will tells the table view how many cells to show.

You want to return the number of items in the array so you use the name of the array followed by “.count”.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     return names.count
}
    
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
     let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
     cell.textLabel?.text = names[indexPath.row]
     return cell
}

In the cellForRowAtIndexPath function you need to return the cell that created earlier in out Table View, to do that you need to create a reference to the cell with the identifier.

The code above needs to returns the cell with the identifier “cell”. I also want to access the cells label attribute and assign a string from the array to it, finally I need to return the cell.

Hit Build and Run and your table view should be running with the names in your array, if you had any problems or errors leave a comment and I will get back to you.

Source Code: http://github.com/GurdevSingh94/UITableView

Post a Comment

You don't have permission to register