Self-Sizing Table View Cells
Learn how to enable self-sizing table view cells and make them resize on-demand while supporting Dynamic Type. By Chuck Krutsinger .
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Self-Sizing Table View Cells
20 mins
- Getting Started
- Looking at the App’s Views
- Creating Self-Sizing Table View Cells
- Adding Constraints to Each Subview
- Configuring the Table View
- Adding a Background
- Adding More User Interfaces
- Adding Views to the Cell
- Adding New Constraints on a Stack View
- Setting the Hugging Priorities
- Populating the New Views
- Expanding Cells
- Implementing Dynamic Type
- Where to Go From Here?
Populating the New Views
Now, you’ll populate the views. Open AuteurTableViewCell.swift. Add the following method:
func configure(
name: String,
bio: String,
sourceText: String,
imageName: String
) -> AuteurTableViewCell {
// 1
nameLabel.text = name
bioLabel.text = bio
sourceLabel.text = sourceText
auteurImageView.image = UIImage(named: imageName)
// 2
nameLabel.textColor = .systemGray2
bioLabel.textColor = .systemGray3
sourceLabel.textColor = .systemGray3
// 3
sourceLabel.font = UIFont.italicSystemFont(
ofSize: sourceLabel.font.pointSize)
nameLabel.textAlignment = .center
// 4
selectionStyle = .none
return self
}
The code above is fairly self-explanatory. You’re simply setting the:
- Contents of each of the views.
- Label text colors to different system colors that adapt to light and dark mode.
- Source label to use an italicized system font.
- Cell selection style to none.
Open AuteurListViewController.swift. Replace tableView(_:cellForRowAt:)
with:
func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "AuteurCell",
for: indexPath
) as? AuteurTableViewCell ?? AuteurTableViewCell(
style: .default, reuseIdentifier: "AuteurCell")
let auteur = auteurs[indexPath.row]
return cell.configure(
name: auteur.name,
bio: auteur.bio,
sourceText: auteur.source,
imageName: auteur.image)
}
This uses configure(name:bio:sourceText:imageName:)
to configure the cell for display.
Build and run.
Not bad, but you can take it to the next level by adding expanding cells to reveal more information about films from an auteur. Your client will love this!
Expanding Cells
Since Auto Layout constraints drive your cell heights and the content of each interface element, expanding the cell is as simple as adding more text to the text view when the user taps that cell.
Open AuteurDetailViewController.swift and add the following extension:
extension AuteurDetailViewController: UITableViewDelegate {
func tableView(
_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath
) {
// 1
guard
let cell = tableView.cellForRow(at: indexPath) as? FilmTableViewCell,
var film = selectedAuteur?.films[indexPath.row]
else {
return
}
// 2
film.isExpanded.toggle()
selectedAuteur?.films[indexPath.row] = film
// 3
tableView.beginUpdates()
cell.configure(
title: film.title,
plot: film.plot,
isExpanded: film.isExpanded,
poster: film.poster)
tableView.endUpdates()
// 4
tableView.scrollToRow(at: indexPath, at: .top, animated: true)
}
}
Here’s what’s happening:
- You ask the tableView for a reference to the cell at the selected indexPath and then get the corresponding
Film
. - Toggle the
isExpanded
state of theFilm
object and add it back into the array — which you need to do because structs are value types. - Next, you tell the table view you’re going to make updates. You reconfigure the cell with the new value for
film.isExpanded
, then tell the table view the updates are complete. This causes the changes to animate. - Finally, tell the table view to scroll to the selected row in an animated fashion.
Now, open FilmTableViewCell.swift. In configure(title:plot:isExpanded:poster:)
, paste the following code at the end of the method:
moreInfoTextView.text = isExpanded ? plot : Self.moreInfoText
moreInfoTextView.textAlignment = isExpanded ? .left : .center
moreInfoTextView.textColor = isExpanded ? .systemGray3 : .systemRed
The code above will reconfigure the cell text, alignment and color based on the value of isExpanded
.
Build and run.
When you tap a film cell, you’ll see it expands to accommodate the full text.
Select an auteur and tap the films. You’ll see some very smooth cell expansion, revealing information about each film.
When you tap a film cell, you’ll see it expands to accommodate the full text. Next, you’ll learn to integrate Dynamic Type in your app to make your app more accessible to a wider audience.
Implementing Dynamic Type
You’ve shown your progress to your client, and they love it! But they have one final request: They want the app to support the Larger Text Accessibility feature. The app needs to adjust to the customer’s preferred reading size.
Introduced in iOS 7, Dynamic Type makes this task easy. It gives developers the ability to specify different text styles for different blocks of text, like Headline or Body, and have that text adjust automatically when the user changes the preferred size in their Device Settings.
Open Main.storyboard. Select the Auteurs Scene. Select the Name Label.
In the Attributes inspector, complete the following steps:
- Click the T button from the Font settings.
- Select Headline under the Text Styles.
- Enable the Automatically Adjusts Font option.
- Set the Lines to 0.
You’ve allowed the name label’s text to adjust its font size using a font that supports Dynamic Type, enabling the setting to grow/shrink the font and wrap the text to the next line if it consumes all the horizontal space on a line.
Do the same with the Bio Label, but choose Body under Text Styles instead of Headline.
The labels in the Auteur Detail View Controller Scene have already been adjusted in the starter project to reduce repetitive tasks.
That’s all you need to do to make the app more accessible. Build and run.
Enter the home screen your simulator/device.
Open the Settings app. Do the following:
- Tap Accessibility ▸ Display & Text Size ▸ Larger Text.
- Enable Larger Accessibility Sizes.
- Drag the slider to the right.
You’ve increased the text size to a large setting.
Open the Auteurs app. Your text will now appear larger. Thanks to your work on implementing dynamically sized cells, the table view still looks great:
Congratulations on completing this tutorial on self-sizing table view cells!
Where to Go From Here?
Download the completed project files by clicking the Download Materials button at the top or bottom of the tutorial.
Table views are perhaps the most fundamental of structured data views in iOS. As your apps get more complex, you’re likely to use all sorts of custom table view cell layouts.
For more about Auto Layout, check out our book Auto Layout by Tutorials.
We hope that you enjoyed this tutorial. If you have any questions or comments, or would like to show off your own self-sizing layouts, join the forum discussion below!