A Table View is a list of rows that can be selected. Each row is populated from a data source. This example creates a simple table view in which each row is a single line of text.
Although there are a number of ways to create a UITableView
, one of the easiest is to add one to a Storyboard. Open your Storyboard and drag a UITableView
onto your UIViewController
. Make sure to use Auto Layout to correctly align the table (pin all four sides).
In order to display content dynamically (i.e. load it from a data source like an array, a Core Data model, a networked server, etc.) in your table view you need to setup the data source.
A data source could, as stated above, be anything with data. Its entirely up to you how to format it and whats in it. The only requirement is that you must be able to read it later so that you can populate each row of your table with data when needed.
In this example, we’ll just set an array with some strings (text) as our data source:
Swift
let myDataArray: [String] = ["Row one", "Row two", "Row three", "Row four", "Row five"]
Objective-C
// You'll need to define this variable as a global variable (like an @property) so that you can access it later when needed.
NSArray *myDataArray = @[@"Row one", @"Row two", @"Row three", @"Row four", @"Row five"];
Make sure your view controller conforms to the UITableViewDataSource
protocol.
Swift
class ViewController: UIViewController, UITableViewDataSource {
Objective-C
@interface ViewController : UIViewController <UITableViewDataSource>
As soon as your view controller has declared it will conform to the UITableViewDataSource
(that’s what we’ve just done above), you are required to implement at least the following methods in your view controller class: