Unit 4: TableViews - Subjective Questions
INT372 — Iphone Application Programming • Practice Questions with Detailed Answers
20 questions
Define UITableView and explain its role in an iPhone application.
UITableView is a UIKit control used to display vertically scrollable data as a sequence of rows.
Its main features are:
- It presents data in one or more sections.
- Each item is displayed using a
UITableViewCell. - It supports plain and grouped presentation styles.
- It reuses cells to reduce memory consumption and improve scrolling performance.
- It supports row selection, editing, insertion, deletion, and reordering.
A table view obtains data through the data source and reports user interactions through the delegate. It is commonly used for contact lists, settings screens, menus, and product catalogs.
Explain the data source and delegate mechanisms of a UITableView.
A UITableView uses two important supporting objects:
1. Data source
The data source supplies the content displayed by the table. It adopts UITableViewDataSource and commonly implements:
tableView(_:numberOfRowsInSection:)to return the number of rows.tableView(_:cellForRowAt:)to create or configure each cell.numberOfSections(in:)to return the number of sections.
2. Delegate
The delegate manages appearance and user interaction. It adopts UITableViewDelegate and may implement:
tableView(_:didSelectRowAt:)for row selection.tableView(_:heightForRowAt:)for row height.- Header and footer display methods.
- Editing and accessory-button interaction methods.
The view controller often acts as both the data source and delegate. They can be connected in Interface Builder or assigned in code using tableView.dataSource = self and tableView.delegate = self.
Describe the steps required to implement a simple table view that displays a list of programming languages.
The basic implementation involves the following steps:
- Add a
UITableViewto the view controller. - Create an array containing the data.
- Adopt
UITableViewDataSourceandUITableViewDelegate. - Assign the table's data source and delegate.
- Implement the required data source methods.
class LanguagesViewController: UIViewController,
UITableViewDataSource,
UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
let languages = ["Swift", "Objective-C", "Python", "Java"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return languages.count
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "LanguageCell",
for: indexPath
)
cell.textLabel?.text = languages[indexPath.row]
return cell
}
}The reuse identifier configured in the storyboard must match LanguageCell.
Explain the purpose of IndexPath in a table view. How are its section and row properties used?
IndexPath identifies the position of an item in a table view. In the context of UITableView, it contains two important values:
section: Identifies the section containing the row.row: Identifies the row within that section.
For example, an index path with section = 1 and row = 2 refers to the third row of the second section because indexing begins at zero.
It is used to:
- Retrieve the correct model object.
- Configure a table cell.
- Detect which row was selected.
- Insert, delete, reload, or move specific rows.
Example:
let item = sectionData[indexPath.section][indexPath.row]
cell.textLabel?.text = itemThus, IndexPath connects a visible cell with its corresponding location in the application's data model.
What is table-view cell reuse? Explain why dequeueReusableCell(withIdentifier:for:) is important.
A table may contain hundreds of rows, but only a small number are visible at one time. Creating a separate cell for every row would waste memory.
Cell reuse solves this problem:
- Cells that move off-screen are placed in a reuse queue.
- When a new row becomes visible, the table view retrieves an available cell from that queue.
- The data source reconfigures the reused cell with the new row's content.
let cell = tableView.dequeueReusableCell(
withIdentifier: "ItemCell",
for: indexPath
)
cell.textLabel?.text = items[indexPath.row]The method dequeueReusableCell(withIdentifier:for:) always returns a cell when the identifier has been registered or created as a storyboard prototype. This mechanism improves:
- Memory efficiency
- Scrolling performance
- Cell creation speed
Every reusable property should be reset during configuration so that old content does not appear in another row.
Distinguish between plain and grouped table-view styles.
The two commonly used UITableView styles are plain and grouped.
| Feature | Plain style | Grouped style |
|---|---|---|
| Appearance | Rows usually extend across the available width | Sections are visually separated into groups |
| Section separation | Mainly indicated by headers and footers | Clear spacing appears between sections |
| Common use | Contacts, messages, search results | Settings forms and categorized options |
| Header behavior | Section headers may remain visible while scrolling | Headers visually belong to individual groups |
| Creation | .plain |
.grouped or .insetGrouped |
Example:
let plainTable = UITableView(frame: .zero, style: .plain)
let groupedTable = UITableView(frame: .zero, style: .grouped)Both styles use the same data source and delegate protocols. The choice primarily depends on the desired organization and visual presentation.
Describe how to organize and display data in multiple grouped sections of a table view.
Sectioned data can be stored as an array of models, where each model contains a section title and its rows.
struct Category {
let title: String
let items: [String]
}
let categories = [
Category(title: "Fruits", items: ["Apple", "Mango"]),
Category(title: "Vegetables", items: ["Carrot", "Potato"])
]The table-view methods can then be implemented as follows:
func numberOfSections(in tableView: UITableView) -> Int {
return categories.count
}
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return categories[section].items.count
}
func tableView(_ tableView: UITableView,
titleForHeaderInSection section: Int) -> String? {
return categories[section].title
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "ItemCell",
for: indexPath
)
cell.textLabel?.text = categories[indexPath.section]
.items[indexPath.row]
return cell
}Creating the table with .grouped or .insetGrouped style visually separates these categories.
Explain how section headers and footers can be added to a UITableView using text.
Text headers and footers can be supplied through UITableViewDataSource methods.
func tableView(_ tableView: UITableView,
titleForHeaderInSection section: Int) -> String? {
return sections[section].title
}
func tableView(_ tableView: UITableView,
titleForFooterInSection section: Int) -> String? {
return "Total items: \(sections[section].items.count)"
}The header generally describes the category of rows in a section, while the footer can provide instructions, summaries, or additional information.
Important points include:
- Return
nilwhen a section does not require a header or footer. - The table view automatically applies system formatting to text headers and footers.
- Header and footer heights may be controlled through delegate methods or table-view properties.
- For advanced formatting, custom header and footer views should be used instead of title methods.
How can a custom view containing a label and an image be used as a table section header?
A custom section header can be returned from the delegate method tableView(_:viewForHeaderInSection:). The view may contain labels, images, buttons, or other controls.
func tableView(_ tableView: UITableView,
viewForHeaderInSection section: Int) -> UIView? {
let header = UIView()
header.backgroundColor = .systemGray6
let imageView = UIImageView(
image: UIImage(systemName: "folder.fill")
)
imageView.frame = CGRect(x: 16, y: 8, width: 24, height: 24)
let label = UILabel(frame: CGRect(x: 52, y: 5,
width: 250, height: 30))
label.text = sections[section].title
label.font = .boldSystemFont(ofSize: 17)
header.addSubview(imageView)
header.addSubview(label)
return header
}
func tableView(_ tableView: UITableView,
heightForHeaderInSection section: Int) -> CGFloat {
return 40
}In production code, Auto Layout or a reusable UITableViewHeaderFooterView subclass is preferable. The custom view replaces the standard text-only header.
Explain how an image can be displayed in a standard UITableViewCell.
A standard table-view cell provides an imageView property. An image can be assigned while configuring the cell.
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "ProductCell",
for: indexPath
)
let product = products[indexPath.row]
cell.textLabel?.text = product.name
cell.imageView?.image = UIImage(named: product.imageName)
return cell
}Images should generally be:
- Properly sized to avoid unnecessary memory use.
- Included in the asset catalog for local resources.
- Loaded asynchronously if downloaded from a network.
- Replaced with a placeholder while remote loading occurs.
For complex layouts, a custom cell with a dedicated UIImageView should be used. When cells are reused, old image requests should be cancelled or verified so that the wrong image is not displayed.
Describe the process of creating and using a custom UITableViewCell containing an image, a title, and a subtitle.
A custom table-view cell is useful when the standard cell styles do not provide the required layout.
Steps:
- Create a subclass of
UITableViewCell. - Add an image view and labels in the storyboard or in code.
- Connect the controls as outlets.
- Set a reuse identifier for the prototype cell.
- Cast the dequeued cell to the custom class and configure it.
class ProductCell: UITableViewCell {
@IBOutlet weak var productImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!
}Configuration:
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(
withIdentifier: "ProductCell",
for: indexPath
) as? ProductCell else {
return UITableViewCell()
}
let product = products[indexPath.row]
cell.titleLabel.text = product.name
cell.subtitleLabel.text = product.details
cell.productImageView.image = UIImage(named: product.imageName)
return cell
}Auto Layout constraints should define the size and position of every element. Reused properties should also be reset in prepareForReuse() when necessary.
Compare the standard cell styles provided by UITableViewCell.
UITableViewCell provides several built-in styles:
.default: Displays a primary text label and an optional image on the left..subtitle: Displays a primary label with a smaller subtitle below it..value1: Displays the main text on the left and detail text on the right. It is useful for settings..value2: Displays a right-aligned primary label and left-aligned detail text.
Example:
let cell = UITableViewCell(style: .subtitle,
reuseIdentifier: "SubtitleCell")
cell.textLabel?.text = "iPhone"
cell.detailTextLabel?.text = "Mobile device by Apple"
cell.imageView?.image = UIImage(systemName: "iphone")Standard styles are suitable for simple interfaces and reduce development effort. A custom subclass is preferable when the row needs multiple images, buttons, special alignment, or a complex responsive layout.
What is an indexed table view? Explain how to add a section index for alphabetical data.
An indexed table view displays an index, usually along the right edge, that allows users to jump quickly to a section. It is commonly used in contact lists.
Suppose the section titles are stored as follows:
let sectionTitles = ["A", "B", "C", "D"]The table first returns section headers:
func tableView(_ tableView: UITableView,
titleForHeaderInSection section: Int) -> String? {
return sectionTitles[section]
}It then supplies the index titles:
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return sectionTitles
}If index entries map directly to table sections, UIKit normally handles the navigation. For a custom mapping, implement:
func tableView(_ tableView: UITableView,
sectionForSectionIndexTitle title: String,
at index: Int) -> Int {
return index
}The underlying data should be grouped and sorted consistently with the index titles.
Explain how to detect the row selected by the user and display the selected item.
Row selection is commonly handled through the delegate method tableView(_:didSelectRowAt:).
func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
let selectedItem = items[indexPath.row]
let alert = UIAlertController(
title: "Selected Item",
message: selectedItem,
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default))
present(alert, animated: true)
tableView.deselectRow(at: indexPath, animated: true)
}For sectioned data, retrieve the item using both values:
let selectedItem = sections[indexPath.section].items[indexPath.row]The selected item may be displayed in an alert, label, detail view, or another view controller. Calling deselectRow(at:animated:) removes the selection highlight after the action is processed.
Describe how to navigate from a selected table row to another view controller using a storyboard segue.
Navigation with a storyboard segue can be implemented as follows:
- Embed the source view controller in a navigation controller.
- Create a segue from the source controller to the detail controller.
- Assign an identifier such as
showDetail. - Detect the selected row.
- Perform the segue and pass the selected model object.
private var selectedProduct: Product?
func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
selectedProduct = products[indexPath.row]
performSegue(withIdentifier: "showDetail", sender: self)
}
override func prepare(for segue: UIStoryboardSegue,
sender: Any?) {
if segue.identifier == "showDetail",
let detailVC = segue.destination as? DetailViewController {
detailVC.product = selectedProduct
}
}If the destination is embedded in another navigation controller, it may be necessary to obtain its visible or top view controller first. The detail controller should expose a property to receive the selected model before its view is loaded.
Explain how to navigate programmatically from a table view to a detail view and pass the selected item.
Programmatic navigation uses a navigation controller's pushViewController(_:animated:) method.
func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
let selectedProduct = products[indexPath.row]
let detailVC = DetailViewController()
detailVC.product = selectedProduct
navigationController?.pushViewController(
detailVC,
animated: true
)
}If the detail controller is defined in a storyboard, instantiate it with its storyboard identifier:
let detailVC = storyboard?.instantiateViewController(
withIdentifier: "DetailViewController"
) as! DetailViewControllerThe source controller then assigns the selected model to a property in the destination controller before pushing it. A navigation controller must contain the source controller; otherwise, navigationController may be nil.
Differentiate between a table's section header and footer, and its tableHeaderView and tableFooterView.
Section headers and footers are different from table-level header and footer views.
Section header and footer:
- Belong to a particular section.
- May appear once for every section.
- Are supplied through methods such as
titleForHeaderInSection,viewForHeaderInSection, andviewForFooterInSection. - Usually describe or summarize one category of rows.
tableHeaderView and tableFooterView:
- Belong to the entire table rather than to a specific section.
- Appear only once.
- Are assigned directly to the table view.
let banner = UIImageView(image: UIImage(named: "banner"))
banner.contentMode = .scaleAspectFill
tableView.tableHeaderView = banner
let footerLabel = UILabel()
footerLabel.text = "End of items"
footerLabel.textAlignment = .center
tableView.tableFooterView = footerLabelA table-level header may contain a banner, search area, or profile summary, while section headers categorize individual groups.
Explain how dynamic row height can be implemented for custom table-view cells.
Dynamic row height allows each cell to expand according to its content. It is especially useful for multi-line labels.
Implementation requirements are:
- Add complete Auto Layout constraints from the top to the bottom of the cell's
contentView. - Set a label's
numberOfLinesto0if it should wrap. - Use automatic dimension for the row height.
- Provide an estimated row height for efficient scrolling.
messageLabel.numberOfLines = 0
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 80Alternatively, the delegate may return automatic dimension:
func tableView(_ tableView: UITableView,
heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}If the vertical constraints are incomplete or conflicting, UIKit cannot calculate the correct height. Fixed heights are simpler but are unsuitable for content whose length varies significantly.
Discuss the important issues that must be considered when customizing reusable table-view cells.
Because cells are reused, customization must be performed carefully.
Important considerations include:
- Configure every visible property in
cellForRowAt, including text, colors, images, and accessory types. - Reset temporary state in
prepareForReuse(). - Avoid storing the row number permanently inside the cell because rows can move.
- Cancel pending image downloads when a cell is reused.
- Use Auto Layout to support different screen sizes and dynamic text.
- Keep expensive operations away from
cellForRowAtto maintain smooth scrolling. - Use a model object to represent cell content.
Example reset:
override func prepareForReuse() {
super.prepareForReuse()
titleLabel.text = nil
subtitleLabel.text = nil
productImageView.image = UIImage(named: "placeholder")
productImageView.alpha = 1.0
}Without proper resetting, reused cells may show stale images, hidden controls, incorrect colors, or selection states from previously displayed rows.
Design a table-view screen that uses grouped sections, custom cells, images, headers, row selection, and navigation to a detail screen. Explain the complete flow.
A complete design may represent a grouped product catalog.
1. Data model
struct Product {
let name: String
let details: String
let imageName: String
}
struct ProductSection {
let title: String
let products: [Product]
}2. Table structure
- Create the table with
.groupedor.insetGroupedstyle. - Return the number of product categories from
numberOfSections(in:). - Return the number of products in each category from
numberOfRowsInSection. - Return each category name from
titleForHeaderInSection.
3. Custom cell
Create a ProductCell containing an image view, title label, and detail label. In cellForRowAt, retrieve the model with:
let product = sections[indexPath.section].products[indexPath.row]Configure the cell's labels and image, ensuring that reusable state is reset correctly.
4. Table header and footer
- Assign a promotional image to
tableHeaderView. - Assign an informational label to
tableFooterView. - Section-specific footers may display the number of products.
5. Selection
In didSelectRowAt, retrieve the same product using indexPath.section and indexPath.row, then remove the highlight with deselectRow(at:animated:).
6. Navigation
Pass the selected Product to a detail view controller through prepare(for:sender:) or assign it before calling pushViewController. The detail view displays the product's large image, title, and full description.
This design combines data source methods, delegate methods, reusable custom cells, grouped sections, visual headers, selection handling, and model-based navigation.
Define UITableView and explain its role in an iPhone application.
UITableView is a UIKit control used to display vertically scrollable data as a sequence of rows.
Its main features are:
- It presents data in one or more sections.
- Each item is displayed using a
UITableViewCell. - It supports plain and grouped presentation styles.
- It reuses cells to reduce memory consumption and improve scrolling performance.
- It supports row selection, editing, insertion, deletion, and reordering.
A table view obtains data through the data source and reports user interactions through the delegate. It is commonly used for contact lists, settings screens, menus, and product catalogs.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →