Avelyn Hyunjeong Choi
Posted on December 6, 2023
Two types of application
- standalone watch app
- companion app (integrate with iPhone app)
2.write ToDo Model in swift
file
// ToDo.swift
import Foundation
struct ToDo: Identifiable {
let id: UUID
var title: String
init(title: String) {
self.id = UUID()
self.title = title
}
}
3.write view in swiftUI
file
// AddToDoView
import SwiftUI
struct AddToDoView: View {
@Binding var todos: [ToDo]
@State private var newToDoTitle = ""
// injects presentationmode environment value (property wrapper)
@Environment(\.presentationMode) var presentationMode
var body: some View {
VStack {
TextField("Enter todo", text: $newToDoTitle)
.padding()
Button("Done") {
if(!newToDoTitle.isEmpty) {
let newToDo = ToDo(title: newToDoTitle)
todos.append(newToDo)
}
// dismiss after new item is added to the array -> returns to the main view
// this value has state of presentationMode
// dismiss: take off the view from the screen. close the current view
presentationMode.wrappedValue.dismiss()
}
.padding()
}
}
}
4.write a main, ContentView
import SwiftUI
struct ContentView: View {
// create an array of todos
@State private var todos = [
ToDo(title: "Buy groceries"),
ToDo(title: "Email John"),
]
// based on this value -> we will either show or don't show the list
@State private var showingAddToDoView = false
var body: some View {
ZStack(alignment: .bottom) { // .bottom -> push button on the bottom
List {
ForEach(todos) { todo in
Text(todo.title)
}.onDelete(perform: delete) // takes a delete function
}
Button(action: {
self.showingAddToDoView.toggle() // toggle the boolean (true -> false)
}) {
Image(systemName: "plus")
.resizable()
.frame(width: 20, height: 20)
.foregroundColor(.white)
.padding()
.background(Color.blue)
.clipShape(Circle())
}
.buttonStyle(.plain) // remove the gray area surrounding the button
.sheet(isPresented: $showingAddToDoView) { // when it's true -> present AddToDoView()
AddToDoView(todos: self.$todos)
}
}
}
// implement delete function
private func delete(at offsets: IndexSet) {
todos.remove(atOffsets: offsets)
}
}
5.demo
💖 💪 🙅 🚩
Avelyn Hyunjeong Choi
Posted on December 6, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.