In this tutorial, we will create a todo list app using Swift and iOS development tools. The app will allow users to add tasks, mark them as completed, and delete them. We will be using Xcode, Apple’s Integrated Development Environment, to write and run our code.
Prerequisites
Before we begin, make sure you have the following tools installed:
- Xcode, which can be downloaded from the Mac App Store or the Apple Developer website.
Let’s get started!
Step 1: Create a New Project
First, open Xcode and select “Create a new Xcode project” from the welcome screen. Choose “App” under the iOS tab, and then select “Single View App”. Click “Next” and fill in the project details.
Make sure to select Swift as the language and Storyboard as the user interface option. Also, choose a product name for your app, such as “TodoListApp”. Finally, select a location to save your project and click “Create”.
Step 2: Design the User Interface
To create the user interface for our app, we will be using Storyboard. Storyboard allows us to visually design our app by dragging and dropping elements onto the canvas.
Open the Main.storyboard file, which should already be open in the editor. There, you will find a blank canvas where you can build your app’s user interface.
First, let’s add a table view to display the list of tasks.
- Drag a Table View from the Object Library on the right side of the screen onto the canvas.
- Resize the table view to fill the whole screen.
- Connect the table view to the view controller by Ctrl-dragging from the table view to the yellow circle at the top of the scene view.
- Choose “delegate” and “dataSource” from the pop-up menu.
Next, let’s add a bar button item to allow users to add new tasks.
- Drag a Navigation Item from the Object Library onto the navigation bar of the view controller.
- Drag a Bar Button Item from the Object Library onto the right side of the navigation item.
- Choose a plus sign icon for the bar button item.
Finally, let’s add a text field and a button to create new tasks.
- Drag a Text Field from the Object Library onto the bottom of the view controller.
- Drag a Button from the Object Library next to the text field.
- Set the button’s title to “Add”.
Congratulations! You have designed the user interface for your todo list app. If you run the app now, you will see an empty table view with a navigation bar and an input field to add new tasks.
Step 3: Create the Model
Now, let’s add some functionality to our app. We will start by creating a model for our tasks.
Create a new Swift file named “Task.swift” in your project, and define a new class called “Task” inside it. This class will represent a single task in our todo list.
class Task {
var title: String
var completed: Bool
init(title: String) {
self.title = title
self.completed = false
}
}
In this code, we have defined a Task
class with two properties: title
and completed
. The title
property represents the title of the task, and the completed
property indicates whether the task has been completed or not. We have also defined an init
method to initialize the task with a given title and set the completed
property to false
by default.
Step 4: Implement the Table View
Now let’s implement the functionality to display and manage the list of tasks in our table view.
Open the ViewController.swift file and add the following code:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var tasks: [Task] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
// MARK: - Table View Data Source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TaskCell", for: indexPath)
let task = tasks[indexPath.row]
cell.textLabel?.text = task.title
cell.accessoryType = task.completed ? .checkmark : .none
return cell
}
// MARK: - Table View Delegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let task = tasks[indexPath.row]
task.completed = !task.completed
tableView.reloadRows(at: [indexPath], with: .automatic)
}
}
In this code, we have created an IBOutlet
for the table view and set the view controller as its delegate and data source in the viewDidLoad
method.
We have also implemented the required methods for the table view’s data source and delegate. The numberOfRowsInSection
method returns the number of tasks in the tasks
array, and the cellForRowAt
method configures each cell with the corresponding task’s title and completed state.
Additionally, we have implemented the didSelectRowAt
method which is called when the user taps on a cell in the table view. In this method, we retrieve the corresponding task, toggle its completed state, and reload the cell to reflect the changes.
Finally, open the Main.storyboard file, select the table view cell, and set its identifier to “TaskCell” in the Attributes inspector.
Run the app, and you should see the tasks being displayed in the table view. You can tap on a task to mark it as completed, and it will be displayed with a checkmark.
Step 5: Add and Delete Tasks
Next, let’s implement the functionality to add new tasks and delete existing tasks.
Open the ViewController.swift file and add the following code:
// MARK: - IBActions
@IBAction func addButtonTapped(_ sender: Any) {
guard let taskTitle = textField.text, !taskTitle.isEmpty else {
return
}
let newTask = Task(title: taskTitle)
tasks.append(newTask)
textField.text = ""
tableView.reloadData()
}
@IBAction func deleteButtonTapped(_ sender: Any) {
if let selectedRows = tableView.indexPathsForSelectedRows {
let sortedIndexes = selectedRows.sorted(by: { $0.row > $1.row })
for indexPath in sortedIndexes {
tasks.remove(at: indexPath.row)
}
tableView.deleteRows(at: sortedIndexes, with: .automatic)
}
}
In this code, we have added two IBActions: addButtonTapped
and deleteButtonTapped
. The addButtonTapped
method is called when the user taps on the “Add” button, and it creates a new task with the text entered in the text field, adds it to the tasks
array, clears the text field, and reloads the table view.
The deleteButtonTapped
method is called when the user taps on the delete button. It retrieves the selected rows from the table view, removes the corresponding tasks from the tasks
array, and deletes the rows from the table view.
To connect these actions to the user interface elements, open the Main.storyboard file, Ctrl-drag from the “Add” button to the view controller, and choose the addButtonTapped
method. Repeat the same process for the delete button, choosing the deleteButtonTapped
method.
Run the app, and you should be able to add new tasks by entering text in the text field and tapping the “Add” button. You can select multiple tasks by tapping on them and delete them by tapping the delete button.
Conclusion
In this tutorial, we have built a simple todo list app using Swift and iOS development tools. We have designed the user interface using Storyboard, created a model for our tasks, implemented the table view to display and manage the tasks, and added functionality to add and delete tasks.
You can continue to enhance this app by adding features such as persisting the tasks using Core Data or connecting it to a server to synchronize the tasks across multiple devices.
I hope you found this tutorial helpful. Happy coding!