Apple Developer Documentation
developer.apple.com
4. Updating App Data
이번 파트에서는 DetailEditView에서 생성한 데이터를 저장하는 방법에 대해 알아보자.
Section 1. Use the Edit View to Create a New Scrum
@State private var isPresentingNewScrumView = false
DetailEditView를 보여줄지 안보여줄지 컨트롤하는 변수를 만들어준다.
@State private var newScrumData = DailyScrum.Data()
var body: some View {
List {
...
}
.navigationTitle("Daily Scrums")
.toolbar {
Button(action: {
isPresentingNewScrumView = true
}) {
Image(systemName: "plus")
}
.accessibilityLabel("New Scrum")
}
.sheet(isPresented: $isPresentingNewScrumView) {
NavigationView {
DetailEditView(data: $newScrumData)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Dismiss") {
isPresentingNewScrumView = false
newScrumData = DailyScrum.Data()
}
}
ToolbarItem(placement: .confirmationAction) {
Button("Add") {
let newScrum = DailyScrum(data: newScrumData)
scrums.append(newScrum)
isPresentingNewScrumView = false
newScrumData = DailyScrum.Data()
}
}
}
}
}
edit 버튼을 눌렀을 때는 isPresentingNewScrumView true로 만들어서 모달 시트를 띄운다.
모달안에 들어가서 Add 버튼을 눌렀을 때는 모달 시트를 닫기 위해 false로 만들어준다. 그리고 새로운 DetailEditView에서 $를 통해 변경된 데이터를 사용해 newScrum을 만들어주고 scrums 배열에 추가해준다.
그리고 newScrumData를 초기화한다.
Dismiss 버튼을 눌렀을 때에는 모달 시트를 닫기 위해 isPresentingNewScrumView 를 false로 해주고 newScrumData를 초기화한다.
Section 2. Add Scrum History
미팅이 끝나면 MeetingView는 미팅 날짜, 기간, 참석자를 기록한다.
그 기록하는 Model을 만들어서 배열로 기록을 할 것이다.
import Foundation
struct History: Identifiable {
let id: UUID
let date: Date
var attendees: [DailyScrum.Attendee]
var lengthInMinutes: Int
init(id: UUID = UUID(), date: Date = Date(), attendees: [DailyScrum.Attendee], lengthInMinutes: Int = 5) {
self.id = id
self.date = date
self.attendees = attendees
self.lengthInMinutes = lengthInMinutes
}
}
id 값을 UUID로 만들기 위해 Identifiable 프로토콜을 준수하게 한다.
let newHistory = History(attendees: scrum.attendees,
lengthInMinutes: scrum.timer.secondsElapsed / 60)
scrum.history.insert(newHistory, at: 0)
init 을 만들어 놓으면 이렇게 초기화가 가능하다.
이후 DetailView 밑에 Section을 추가해서 history를 기록한다.
Section(header: Text("History")) {
if scrum.history.isEmpty {
Label("No meetings yet", systemImage: "calendar.badge.exclamationmark")
}
ForEach(scrum.history) { history in
HStack {
Image(systemName: "calendar")
Text(history.date, style: .date)
}
}
}
'iOS > iOS App Dev Tutorials' 카테고리의 다른 글
[iOS App Dev Tutorials] SwiftUI - Persistence and Concurrency (2) (0) | 2022.05.18 |
---|---|
[iOS App Dev Tutorials] SwiftUI - Persistence and Concurrency (1) (0) | 2022.05.18 |
[iOS App Dev Tutorials] SwiftUI - State Management (3) (0) | 2022.05.18 |
[iOS App Dev Tutorials] SwiftUI - State Management (2) (0) | 2022.05.18 |
[iOS App Dev Tutorials] SwiftUI - State Management (1) (0) | 2022.05.18 |