Share
Explore

LAB: Table Views and Data Sources

Last edited 157 days ago by System Writer
When done: For each Lab: Zip up each Lab Project - GIve the file a meaningful name upload the zip to:

Learning Outcomes:

In this lab, you will develop a table view app for iOS using Xcode by creating a new project, designing a table view within the storyboard, connecting the table view to a view controller, and populating the table view with data from an array of Pokemon names as the data source.
You will also connect the "dataSource" outlet to the "TableViewController" object in the scene. By following these steps, you will gain practical experience in developing iOS applications using Xcode and applying the Model-View-Controller (MVC) design pattern.
This lab allows us to better understand the process of creating and customizing table view apps for iOS devices.
In this lab, we will create a table view app in Xcode that displays a list of Pokemon names. Follow the detailed steps below to accomplish this:

Step 1: Create a new project in Xcode

Open Xcode and select "Create a new Xcode project."
Choose the "Single View App" template and click "Next."
Enter a name for your project (e.g., "PokemonTableView") and click "Next."
Choose a location to save your project and click "Create."

Step 2: Design the interface

In the "Main.storyboard" file, delete the default view controller.
Drag a "Table View Controller" from the Object Library onto the canvas.
Select the table view controller, then check the "Is Initial View Controller" box in the Attributes Inspector.
Click on the table view cell and set the "Style" to "Subtitle" in the Attributes Inspector.
Set the "Identifier" of the table view cell to "Cell" for later use in the code.

Step 3: Create a TableViewController class

In the "Project Navigator," right-click the project folder and select "New File."
Choose "Cocoa Touch Class," click "Next," and name the class "TableViewController."
Make sure it's a subclass of UITableViewController, then click "Next" and "Create."
In the "Main.storyboard" file, select the table view controller, and in the Identity Inspector, set the "Class" to "TableViewController."

Step 4: Connect the data source

In the "TableViewController.swift" file, create a property called "dataSource" and populate it with an array of Pokemon names.
class TableViewController: UITableViewController {

let dataSource = ["Pikachu", "Bulbasaur", "Charmander", "Squirtle", "Jigglypuff"]

}



Step 5: Implement table view data source methods

In the "TableViewController.swift" file, implement the "numberOfRowsInSection" and "cellForRowAt" methods to populate the table view with data from the Pokemon names array.
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = dataSource[indexPath.row]
return cell
}


Step 6: Connect the table view's data source and delegate
In the "Main.storyboard" file, select the table view and control-drag from the table view to the yellow circle at the top of the Table View Controller, then release.
In the pop-up menu, click on "dataSource" to connect the data source.
Repeat the process and click on "delegate" to connect the delegate.

Step 7: Run the app
Click the "Play" button in the toolbar to build and run the app in the iOS Simulator (or on a physical iOS device if connected).
Observe the table view displaying the list of Pokemon names.
In conclusion, this lab demonstrates how to create a simple table view app in Xcode using a data source consisting of an array of Pokemon names.
By following these steps, you can build more complex table views and connect them to more advanced data sources.


Lab Activity: "Dynamic Editable Views: Designing a Responsive iOS Interface"

In this lab, we will explore transforming a view-only list of details into an editable list of controls by adding capabilities to the app's editing mode [1]. We will walk through the process of building an interactive user interface, using Auto Layout constraints to design adaptable and responsive views [3].
By the end of this lab, you will have gained hands-on experience in creating and customizing iOS views, making them editable, and incorporating Auto Layout constraints for a more versatile and user-friendly application.
References:
Lab Activity: Customizing and Animating iOS Views

Learning Outcomes:
In this lab, you will learn how to customize iOS views, create animations, and manage view hierarchy to create an engaging and interactive user interface.

Lab Steps:
Creating a new Xcode project:
Open Xcode and create a new Single View App project.
Name the project "CustomViews" and choose a location to save it.

Designing the custom view:
Create a new Swift file in your project and name it "CustomView.swift".
Import UIKit and subclass UIView to create your custom view class. Add properties and methods to customize the appearance and behavior of the view.

import UIKit

class CustomView: UIView {
// Add properties and methods for your custom view
}


Adding the custom view to the storyboard:

Open Main.storyboard and drag a new UIView from the Object Library onto the ViewController scene.
In the Identity Inspector, set the class of the new UIView to "CustomView".

Customizing the appearance of the custom view:

In CustomView.swift, override the draw(_ rect: CGRect) method to customize the appearance of the view. You can draw shapes, lines, or text using Core Graphics or UIKit drawing functions.

override func draw(_ rect: CGRect) {
// Custom drawing code
}

Try to complete the above code by yourself, then compare with the completed solution:
In this example, we'll create a custom view that draws a filled circle with a centered label. You can adjust the drawing properties according to your needs.

import UIKit

class CustomView: UIView {
var labelText: String = "Custom"
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func draw(_ rect: CGRect) {
// Custom drawing code
// Set the circle color and draw a filled circle
UIColor.blue.setFill()
let circlePath = UIBezierPath(ovalIn: rect.insetBy(dx: 10, dy: 10))
circlePath.fill()
// Set the text attributes (e.g., font, color, alignment)
let textAttributes: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 18),
.foregroundColor: UIColor.white
]
// Create an NSAttributedString with the labelText and textAttributes
let attributedText = NSAttributedString(string: labelText, attributes: textAttributes)
// Calculate the position to center the text within the view
let textSize = attributedText.size()
let textOrigin = CGPoint(x: (rect.width - textSize.width) / 2, y: (rect.height - textSize.height) / 2)
// Draw the text at the calculated position
attributedText.draw(at: textOrigin)
}
}
In this code, we create a UIBezierPath to draw a filled circle and set the fill color to blue. We then define text attributes for font, color, and create an NSAttributedString using the labelText property and the text attributes. We calculate the position to center the text within the view and draw the text at the calculated position.

Creating view animations:

In your ViewController.swift, import UIKit and create a function that will animate your custom view. Use UIView.animate(withDuration:animations:completion:) or other similar methods to create the desired animation.

import UIKit

class ViewController: UIViewController {
@IBOutlet weak var customView: CustomView!

@IBAction func animateButtonTapped(_ sender: UIButton) {
animateCustomView()
}

func animateCustomView() {
// Animation code
}
}

Try to code this by yourself.
Compare with the completed code here:
In this example, we'll create a simple animation that changes the background color and scales the custom view. You can adjust the animation properties according to your needs.
import UIKit

class ViewController: UIViewController {
@IBOutlet weak var customView: CustomView!

@IBAction func animateButtonTapped(_ sender: UIButton) {
animateCustomView()
}

func animateCustomView() {
// Animation code
UIView.animate(withDuration: 0.5, animations: {
// Change the background color of the custom view
self.customView.backgroundColor = UIColor.red

// Scale the custom view
self.customView.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
}, completion: { _ in
// Revert the changes after a short delay
UIView.animate(withDuration: 0.5, delay: 0.5, options: [], animations: {
self.customView.backgroundColor = UIColor.white
self.customView.transform = CGAffineTransform.identity
}, completion: nil)
})
}
}

In this code, we use UIView.animate to change the background color and scale of the customView. The animation lasts for 0.5 seconds. After the first animation is completed, we revert the changes in another 0.5-second animation with a 0.5-second delay.
This is just a simple example, and you can modify the animation properties to create more complex animations or chain multiple animations together.

Connecting the animation function to a button:

In Main.storyboard, drag a UIButton onto the ViewController scene.
Create an IBOutlet for your CustomView and an IBAction for the button in ViewController.swift.
Connect the UIButton to the IBAction and the CustomView to the IBOutlet using Interface Builder.

Testing the app:
Run the app on the iOS Simulator or a physical device to test the custom view and animations.
By completing this lab, you will have learned how to create and customize iOS views, add animations, and manage view hierarchy to create an interactive user interface. This knowledge will help you build more visually appealing and engaging iOS applications.


LAB: "Mastering the TableView Controller: A Comprehensive iOS Lab Activity"


Introduction:
In this lab, we will create an iOS app that uses a TableView Controller to display a list of items. We will cover creating a custom table view cell, handling user interactions, and implementing various UITableView delegate methods to create a feature-rich table view experience.
Setting up the project:

Create a new iOS project in Xcode using the "Single View App" template.
Name your project "TableViewMaster" and save it.

Adding the TableView Controller to the storyboard:
Open the project's Main.storyboard file.
Delete the existing "View Controller" from the storyboard.
Drag a "Table View Controller" from the Object Library onto the storyboard.
In the "Identity Inspector," set the "Storyboard ID" to "TableViewController."
Set the "Table View Controller" as the initial view controller by checking "Is Initial View Controller" in the "Attributes Inspector."

Creating a custom TableViewCell:

Right-click on your project folder in the Navigator area and select "New File."
Choose "Cocoa Touch Class" and name it "CustomTableViewCell."
Set the subclass to "UITableViewCell" and select "Swift" as the language.
In the Main.storyboard, click on the table view cell in the table view controller and set the "Class" to "CustomTableViewCell" in the "Identity Inspector."
Set the "Reuse Identifier" to "CustomCell" in the "Attributes Inspector."

Designing the custom TableViewCell:

Add UI elements such as labels, image views, and buttons to the table view cell in the storyboard.
Create IBOutlet connections between the UI elements and the CustomTableViewCell.swift file.

Connecting the TableView Controller to the custom cell:

Create a new Swift file named "TableViewController.swift."
Set the class to inherit from UITableViewController.
In the Main.storyboard, select the table view controller and set the "Class" to "TableViewController" in the "Identity Inspector."
In the TableViewController.swift file, override the following methods:
The completed code is provided below. Based on your previous lab activities: Can you do this by yourself before comparing to the solution code?
override func numberOfSections(in tableView: UITableView) -> Int {
// Return the number of sections in the table view.
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Create and configure a custom table view cell with data.
}


Populating the table view with data:
Create a data model to represent the items displayed in the table view.
In the TableViewController.swift file, create an array of data model objects.
In the tableView(_:numberOfRowsInSection:) method, return the count of items in the data array.
In the tableView(_:cellForRowAt:) method, dequeue a reusable cell with the "CustomCell" identifier, configure it with the corresponding data model object, and return the cell.
Handling user interactions:
Implement UITableViewDelegate methods to handle user interactions such as row selection and accessory button taps.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Handle the row selection.
}

override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
// Handle the accessory button tap.
}


Testing the app:
Run the app on the iOS Simulator or a physical device to test the table view controller and custom table view cell.

By completing this lab, you will have a solid understanding of how to create and customize table view controllers, design custom table view cells, and handle user interactions in a feature-rich iOS app.

Here is the completed code for this Lab. Can you code the starter lab by yourself before comparing to this?


Here is the completed code for the methods in TableViewController.swift:
import UIKit

class TableViewController: UITableViewController {

let items = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"]

override func numberOfSections(in tableView: UITableView) -> Int {
// Return the number of sections in the table view.
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return items.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Create and configure a custom table view cell with data.
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableViewCell
cell.titleLabel.text = items[indexPath.row]
return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Handle the row selection.
tableView.deselectRow(at: indexPath, animated: true)
let selectedItem = items[indexPath.row]
print("Selected item: \(selectedItem)")
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.