tvOS Fundamentals - Creating a UITableView with Swift 4

In this first video in our tvOS Fundamentals series, we’ll create a UITableView. Learn how to populate the cell text of each row with a String from an array, then detect which cell is currently highlighted or pressed down on with the Apple remote.

Don’t forget you can watch this course on our new CartoonSmart TV app available for iOS and tvOS.

Example Code

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var tableView:UITableView!

var mainCategories = [String]()


override func viewDidLoad() {


// Do any additional setup after loading the view, typically from a nib.


mainCategories = ["Podcasts","Recent","Free","YouTube","Favorites","Paid"]







func setUpTableView(){


let tableFrame:CGRect = CGRect(x: 0, y: 120, width: (self.view.frame.width / 3) – 50 , height: self.view.frame.height – 450)

tableView = UITableView(frame: tableFrame, style: .grouped)



self.tableView.dataSource = self

self.tableView.delegate = self





//MARK: ————-Table stuff



func numberOfSections(in tableView: UITableView) -> Int {

//1 column

return 1



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


return mainCategories.count




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


let cell = UITableViewCell(style:  .subtitle, reuseIdentifier: nil)

cell.textLabel?.text = "\( mainCategories[indexPath.row] )"


return cell




func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {

//this runs on press

print (indexPath.item)

print( mainCategories[indexPath.item] )




func tableView(_ tableView: UITableView, didUpdateFocusIn context: UITableViewFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {


//runs anytime we move up or down the table view



if ( context.nextFocusedIndexPath == nil){

print ("not browsing the table")




print ( context.nextFocusedIndexPath!.item )

//use that number to populate something else probably according to the category.






override func didReceiveMemoryWarning() {


// Dispose of any resources that can be recreated.



Tags: UITableView, didUpdateFocus, nextFocusedIndexPath, UITableViewDataSource, UITableViewDelegate, cellForRowAt

Download the new CartoonSmart TV App - Organize all your FREE and Premium Lessons

Get it!