I am the author of iOS 17 Fundamentals, Building iOS User Interfaces with SwiftUI, and eight other courses on Pluralsight.
Deepen your understanding by watching!
Swift UITableViewDataSource Cheat Sheet
iOS developers will quickly recognize that there are a set of methods that always tend to get implemented when dealing with UITableViews
. The problem I consistently face is remembering that set of methods that belong to the UITableViewDataSource
(and UITableViewDelegate
) protocols. I find myself option-clicking the protocol name to remember the method signatures I need, since Xcode doesn’t have a way to stub out the methods involved with a protocol (C# developers working in Visual Studio like myself are spoiled!).
I’m sure cheat sheets like this already exist, but I thought, “Why not have one that I can reference from my own blog?”… In fact, I’ve gone ahead and turned the code below into a snippet in Xcode, but just in case I ever lose that, I’ve got this post, which stubs out dummy implementations of the three most common UITableViewDataSource
protocol methods.
I’d be delighted if it helped my readers as well, so without further ado, here’s my UITableViewDataSource
cheat sheet, which should allow you (and me) to copy and paste directly into our UITableViewDataSource
class for a quick start:
1func numberOfSectionsInTableView(tableView: UITableView) -> Int {
2 return 1 // This was put in mainly for my own unit testing
3}
4
5func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
6 return dataSourceArray.count // Most of the time my data source is an array of something... will replace with the actual name of the data source
7}
8
9func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
10 // Note: Be sure to replace the argument to dequeueReusableCellWithIdentifier with the actual identifier string!
11 let cell = tableView.dequeueReusableCellWithIdentifier("ReplaceWithCellIdentifier") as! UITableViewCell
12
13 // set cell's textLabel.text property
14 // set cell's detailTextLabel.text property
15 return cell
16}