如何使用Swift建立一个任务的iOS应用程序

377 阅读4分钟

使用Swift构建一个iOS任务应用程序

iOS是当今使用最多的移动平台之一,与Android并列。iOS应用开发主要使用XCode和Swift。XCode是苹果公司开发的IDE,用于为iOS和他们的一些其他平台(如macOS)开发丰富和高性能的应用程序。

Swift是作为Objective-C的替代品而开发的,是iOS开发的一种主要语言。让我们通过使用Swift建立一个任务应用来学习iOS应用开发。

目标

在这篇文章中,我们旨在完成以下任务。

  • 理解iOS应用开发的工作流程。
  • 使用Swift开发一个具有添加和删除任务等功能的任务应用程序。

前提条件

  • 一台运行macOS的机器。
  • 对Swift语言有基本了解。
  • 一个工作的XCode安装。

建立一个项目

现在让我们开始设置一个新项目。

  • 打开XCode。
  • 现在,点击 "创建一个新的XCode项目"。

Creating a new project

  • 让我们使用iOS > App模板。

iOS App Template

  • 让我们将我们的应用程序命名为 "AwesomeToDo"。选择其他设置,如下图所示。

Initial App Settings

  • 点击 "创建"。

实施和编码

让我们直接进入应用程序的编程。现在,一旦我们创建了这个项目,XCode就会把我们带到IDE的主窗口。

XCode Main Window

开始使用

要开始,请点击右窗格上的ContentView.swift 文件。该文件由项目的初始用户界面组成,其中定义了视图。它由一个结构组成,ContentView ,其中定义了视图。

struct ContentView: View {
    // The body of ContentView is defined below
    var body: some View {
        // A Text View that displays "Hello World"
        Text("Hello World")
    }
}

此外还有一个ContentView_Previews 结构。这将产生一个ContentView 的实例。

// The PreviewProvider is used to generate a preview
struct ContentView_Previews: PreviewProvider {
    // The below line produces a preview on the `Canvas`
    static var previews: some View {
        ContentView()
    }
}

现在,让我们来定义我们的ContentView。我们将利用SwiftUI,一个由苹果公司开发的UI工具包,以加速iOS应用程序的开发。

ContentView.swift

// Importing SwiftUI
import Swift

// Combine is used to handle asynchronous events
import Combine

struct ContentView: View {
    // @ObservedObject is a property wrapper that gives the views (User Interface) a way to watch the state of an object. For example, a datastore.
    // Here we create a taskStore observedObject that references to TaskDataStore (We will be defining this later on). 
    @ObservedObject var taskStore = TaskDataStore()

    // The state property wrapper is used to move the variable storage outside of the current struct into shared storage.
    // We create a variable newTask to maintain the current task that is entered on the screen.
    @State var newTask : String = ""
    
    // This view defines a taskbar, which will be used to enter tasks and add them.
    var addTaskBar : some View {
        // HStack arranges the items horizontally.
        HStack {
            // the self.$newTask binds the content of the textbox to the newTask state variable.
            TextField("Add Task: ", text: self.$newTask)
            // Whenever the button is clicked, it fires the addNewTask function.
            Button(action: self.addNewTask, label: {
                Text("Add New")
            })
        }
    }

    // Body of the ContentView
    var body: some View {
        // A View that can be used in a scenario where a user would want to move across views.
        NavigationView {
            // A VStack arranges the elements vertically.
            VStack {
                // Here, we call the function, addTaskBar.
                addTaskBar.padding()
                // A List is used to present data in a single column.
                List {
                    // ForEach is used to loop over a collection of items to create views.
                    ForEach(self.taskStore.tasks) { task in
                        // The Task string is displayed as text.
                        Text(task.taskItem)
                    }.onDelete(perform: self.deleteTask) // We also define a delete event that can performs the deleteTask function.
                }.navigationBarTitle("Tasks").navigationBarItems(trailing: EditButton())
                // We name the navbar as Tasks and add an edit button (this is provided by the SwiftUI library)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

创建DataStore

创建一个新的Swift文件,并将其命名为DataStore.swift 。在这里,我们必须定义数据存储,任务项将被存储在这里。我们将导入Foundation 库,它提供了一个数据存储层。

import Foundation
import SwiftUI
import Combine

// Here we define an ID and a TaskItem for every Task.
struct Task : Identifiable {
    var id = String()
    var taskItem = String()
}

// We define the DataStore as an array of Tasks.
class TaskDataStore: ObservableObject {
    // @Published is a property wrapper that announces when changes occur to the DataStore.
    @Published var tasks = [Task]()
}

创建AddTask和DeleteTask函数

现在让我们为我们的任务应用程序添加核心功能。

这包括以下两个功能。

  • addNewTask
  • deleteTask
func addNewTask() {
    // This accesses the dataStore and appends a new task to it.
    taskStore.tasks.append(Task(
        // We maintain an ID and taskItem, as defined in the DataStore.
        id: String(taskStore.tasks.count + 1),
        taskItem: newTask
    ))
    // This line sets newTask to an empty string
    // When we add the task to the list, it erases the textbox
    self.newTask = ""
}

// at offsets deletes the task at the offset where you clicked the delete button
func deleteTask(at offsets: IndexSet) {
    taskStore.tasks.remove(atOffsets: offsets)
}

构建和运行该应用程序

现在,要运行我们的应用程序,请点击产品>运行选项,或使用快捷键Command + R 来构建和运行应用程序。它将在一个模拟器中打开该应用程序。

总结

  • 我们为iOS开发设置了XCode IDE。
  • 我们学习了如何在一个iOS应用程序中实现不同的视图。
  • 我们使用SwiftUI构建了一个功能齐全的iOS应用程序。