โreturn Binding
SwiftUI โฉ Data Flow โฉ Binding โฉ return Binding
๐ ๅ่๏ผSwift Playgrounds (Date Planner - Event Data)
class EventData: ObservableObject {
@Published var events: [Event] = [ ... ]
// omitted ...
// โญ๏ธ ็ฅๅฅ็ method๏ผ
// 1. ๅๅณ็ๅๅฅๆฏ Binding<[Event]>
// 2. Binding<[Event]>(get: {}, set: {}) ่ชๆณโ๏ธโ๏ธโ๏ธ
// โญโโโโ โญ๏ธ 1 โโโโโฎ
func sortedEvents(period: Period) -> Binding<[Event]> {
// โญโโโโ โญ๏ธ 2 โโโโโฎ
Binding<[Event]>(
// โญ๏ธ get: read binding data
get: {
self.events
.filter {
switch period {
case .nextSevenDays:
return $0.isWithinSevenDays
case .nextThirtyDays:
return $0.isWithinSevenToThirtyDays
case .future:
return $0.isDistant
case .past:
return $0.isPast
}
}
.sorted { $0.date < $1.date }
},
// โญ๏ธ set: write binding data
set: { events in
for event in events {
if let index = self.events.firstIndex(where: { $0.id == event.id }) {
self.events[index] = event
}
}
}
)// end: Binding<[Event]>()
}// end: sortedEvents()
}
ๅฆไฝไฝฟ็จๅณๅ็ Binding<[Event]>
๏ผ
struct EventList: View {
@EnvironmentObject var eventData: EventData
@State private var isAddingNewEvent = false
@State private var newEvent = Event()
var body: some View {
List {
ForEach(Period.allCases) { period in
if !eventData.sortedEvents(period: period).isEmpty {
Section(content: {
// โญโโโโโโโ โญ๏ธ Binding<[Event]> โโโโโโโโโฎ โญโโญ๏ธโโฎ
ForEach(eventData.sortedEvents(period: period)) { $event in
// โญ๏ธ โฒ
NavigationLink {
// two-way binding โญโโญ๏ธโโฎ
EventEditor(event: $event)
} label: {
// one-way โญโญ๏ธโโฎ
EventRow(event: event)
}
.swipeActions {
Button(role: .destructive) {
eventData.delete(event)
} label: {
Label("Delete", systemImage: "trash")
}
}
}
}, header: {
Text(period.name)
.font(.callout)
.foregroundColor(.secondary)
.fontWeight(.bold)
})
}
}
}
.navigationTitle("Date Planner")
.toolbar {
ToolbarItem {
Button {
newEvent = Event()
isAddingNewEvent = true
} label: {
Image(systemName: "plus")
}
}
}
.sheet(isPresented: $isAddingNewEvent) {
NavigationView {
EventEditor(event: $newEvent, isNew: true)
}
}
}
}
SwiftUI โฉ State and Data Flow โฉ
Last updated