Unit 4 subjective questions TableViews
INT372 — Iphone Application Programming 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Define
UITableViewand explain its role in an iPhone application.Model answer
UITableViewis 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.
-
Question 2 of 20
Explain the data source and delegate mechanisms of a
UITableView.Model answer
A
UITableViewuses two important supporting objects:1. Data source
The data source supplies the content displayed by the table. It adopts
UITableViewDataSourceand 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
UITableViewDelegateand 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 = selfandtableView.delegate = self. -
Question 3 of 20
Describe the steps required to implement a simple table view that displays a list of programming languages.
Model answer
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.
Swiftclass 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. - Add a
-
Question 4 of 20
Explain the purpose of
IndexPathin a table view. How are itssectionandrowproperties used?Model answer
IndexPathidentifies the position of an item in a table view. In the context ofUITableView, 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 = 1androw = 2refers 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:
Swiftlet item = sectionData[indexPath.section][indexPath.row] cell.textLabel?.text = itemThus,
IndexPathconnects a visible cell with its corresponding location in the application's data model. -
Question 5 of 20
What is table-view cell reuse? Explain why
dequeueReusableCell(withIdentifier:for:)is important.Model answer
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.
Swiftlet 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.
-
-
Question 6 of 20
Distinguish between plain and grouped table-view styles.
Model answer
The two commonly used
UITableViewstyles 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.groupedor.insetGroupedExample:
Swiftlet 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.
-
Question 7 of 20
Describe how to organize and display data in multiple grouped sections of a table view.
Model answer
Sectioned data can be stored as an array of models, where each model contains a section title and its rows.
Swiftstruct 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:
Swiftfunc 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
.groupedor.insetGroupedstyle visually separates these categories. -
Question 8 of 20
Explain how section headers and footers can be added to a
UITableViewusing text.Model answer
Text headers and footers can be supplied through
UITableViewDataSourcemethods.Swiftfunc 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.
- Return
-
Question 9 of 20
How can a custom view containing a label and an image be used as a table section header?
Model answer
A custom section header can be returned from the delegate method
tableView(_:viewForHeaderInSection:). The view may contain labels, images, buttons, or other controls.Swiftfunc 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
UITableViewHeaderFooterViewsubclass is preferable. The custom view replaces the standard text-only header. -
Question 10 of 20
Explain how an image can be displayed in a standard
UITableViewCell.Model answer
A standard table-view cell provides an
imageViewproperty. An image can be assigned while configuring the cell.Swiftfunc 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
UIImageViewshould be used. When cells are reused, old image requests should be cancelled or verified so that the wrong image is not displayed. -
Question 11 of 20
Describe the process of creating and using a custom
UITableViewCellcontaining an image, a title, and a subtitle.Model answer
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.
Swiftclass ProductCell: UITableViewCell { @IBOutlet weak var productImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subtitleLabel: UILabel! }Configuration:
Swiftfunc 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. - Create a subclass of
-
Question 12 of 20
Compare the standard cell styles provided by
UITableViewCell.Model answer
UITableViewCellprovides 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:
Swiftlet 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.
-
Question 13 of 20
What is an indexed table view? Explain how to add a section index for alphabetical data.
Model answer
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:
Swiftlet sectionTitles = ["A", "B", "C", "D"]The table first returns section headers:
Swiftfunc tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sectionTitles[section] }It then supplies the index titles:
Swiftfunc 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:
Swiftfunc 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.
-
Question 14 of 20
Explain how to detect the row selected by the user and display the selected item.
Model answer
Row selection is commonly handled through the delegate method
tableView(_:didSelectRowAt:).Swiftfunc 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:
Swiftlet 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. -
Question 15 of 20
Describe how to navigate from a selected table row to another view controller using a storyboard segue.
Model answer
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.
Swiftprivate 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.
-
Question 16 of 20
Explain how to navigate programmatically from a table view to a detail view and pass the selected item.
Model answer
Programmatic navigation uses a navigation controller's
pushViewController(_:animated:)method.Swiftfunc 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:
Swiftlet 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,
navigationControllermay benil. -
Question 17 of 20
Differentiate between a table's section header and footer, and its
tableHeaderViewandtableFooterView.Model answer
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.
tableHeaderViewandtableFooterView:- Belong to the entire table rather than to a specific section.
- Appear only once.
- Are assigned directly to the table view.
Swiftlet 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.
-
Question 18 of 20
Explain how dynamic row height can be implemented for custom table-view cells.
Model answer
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.
SwiftmessageLabel.numberOfLines = 0 tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 80Alternatively, the delegate may return automatic dimension:
Swiftfunc 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.
- Add complete Auto Layout constraints from the top to the bottom of the cell's
-
Question 19 of 20
Discuss the important issues that must be considered when customizing reusable table-view cells.
Model answer
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:
Swiftoverride 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.
- Configure every visible property in
-
Question 20 of 20
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.
Model answer
A complete design may represent a grouped product catalog.
1. Data model
Swiftstruct 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
ProductCellcontaining an image view, title label, and detail label. IncellForRowAt, retrieve the model with:Swiftlet 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 usingindexPath.sectionandindexPath.row, then remove the highlight withdeselectRow(at:animated:).6. Navigation
Pass the selected
Productto a detail view controller throughprepare(for:sender:)or assign it before callingpushViewController. 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.
- Create the table with
That's unit 4
Long answers stick best when they're tested again soon. Run the MCQs on this unit, then come back to the questions you found hardest.
Nearly through. Did unit 4 of INT372 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 4 of INT372 save you a night before the exam?
Then you can help keep it free for the next batch. 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.