Swiftui Reorder List Dynamic Sections from Another View

SwiftUI Reorder list dynamic sections from another view

The problem of this scenario is recreated many times ViewModel, so modifications made in sheet just lost. (The strange thing is that in SwiftUI 2.0 with StateObject these changes also lost and EditButton does not work at all.)

Anyway. It looks like here is a found workaround. The idea is to break interview dependency (binding) and work with pure data passing them explicitly into sheet and return them back explicitly from it.

Tested & worked with Xcode 12 / iOS 14, but I tried to avoid using SwiftUI 2.0 features.

class ViewModel: ObservableObject {
@Published var sections = ["S1", "S2", "S3", "S4"]

func move(from source: IndexSet, to destination: Int) {
sections.move(fromOffsets: source, toOffset: destination)
}
}

struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
@State var showOrderingView = false

var body: some View {
VStack {
Button("Reorder sections") {
self.showOrderingView = true
}

list
}
.sheet(isPresented: $showOrderingView) {
OrderingView(sections: viewModel.sections) {
self.viewModel.sections = $0
}
}
}

var list: some View {
List {
ForEach(viewModel.sections, id: \.self) { section in
Section(header: Text(section)) {
ForEach(0 ..< 3, id: \.self) { _ in
Text("Item")
}
}
}
}
}
}

struct OrderingView: View {
@State private var sections: [String]
let callback: ([String]) -> ()

init(sections: [String], callback: @escaping ([String]) -> ())
{
self._sections = State(initialValue: sections)
self.callback = callback
}

var body: some View {
NavigationView {
List {
ForEach(sections, id: \.self) { section in
Text(section)
}
.onMove {
self.sections.move(fromOffsets: $0, toOffset: $1)
}
}
.navigationBarItems(trailing: EditButton())
}
.onDisappear {
self.callback(self.sections)
}
}
}

How to dynamically create sections in a SwiftUI List/ForEach and avoid Unable to infer complex closure return type

In reference to my comment on your question, the data should be put into sections before being displayed.

The idea would be to have an array of objects, where each object contains an array of occurrences. So we simplify your occurrence object (for this example) and create the following:

struct Occurrence: Identifiable {
let id = UUID()
let start: Date
let title: String
}

Next we need an object to represent all the occurrences that occur on a given day. We'll call it a Day object, however the name is not too important for this example.

struct Day: Identifiable {
let id = UUID()
let title: String
let occurrences: [Occurrence]
let date: Date
}

So what we have to do is take an array of Occurrence objects and convert them into an array of Day objects.

I have created a simple struct that performs all the tasks that are needed to make this happen. Obviously you would want to modify this so that it matches the data that you have, but the crux of it is that you will have an array of Day objects that you can then easily display. I have added comments through the code so that you can clearly see what each thing is doing.

struct EventData {
let sections: [Day]

init() {
// create some events
let first = Occurrence(start: EventData.constructDate(day: 5, month: 5, year: 2019), title: "First Event")
let second = Occurrence(start: EventData.constructDate(day: 5, month: 5, year: 2019, hour: 10), title: "Second Event")
let third = Occurrence(start: EventData.constructDate(day: 5, month: 6, year: 2019), title: "Third Event")

// Create an array of the occurrence objects and then sort them
// this makes sure that they are in ascending date order
let events = [third, first, second].sorted { $0.start < $1.start }

// create a DateFormatter
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none

// We use the Dictionary(grouping:) function so that all the events are
// group together, one downside of this is that the Dictionary keys may
// not be in order that we require, but we can fix that
let grouped = Dictionary(grouping: events) { (occurrence: Occurrence) -> String in
dateFormatter.string(from: occurrence.start)
}

// We now map over the dictionary and create our Day objects
// making sure to sort them on the date of the first object in the occurrences array
// You may want a protection for the date value but it would be
// unlikely that the occurrences array would be empty (but you never know)
// Then we want to sort them so that they are in the correct order
self.sections = grouped.map { day -> Day in
Day(title: day.key, occurrences: day.value, date: day.value[0].start)
}.sorted { $0.date < $1.date }
}

/// This is a helper function to quickly create dates so that this code will work. You probably don't need this in your code.
static func constructDate(day: Int, month: Int, year: Int, hour: Int = 0, minute: Int = 0) -> Date {
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
dateComponents.timeZone = TimeZone(abbreviation: "GMT")
dateComponents.hour = hour
dateComponents.minute = minute

// Create date from components
let userCalendar = Calendar.current // user calendar
let someDateTime = userCalendar.date(from: dateComponents)
return someDateTime!
}

}

This then allows the ContentView to simply be two nested ForEach.

struct ContentView: View {

// this mocks your data
let events = EventData()

var body: some View {
NavigationView {
List {
ForEach(events.sections) { section in
Section(header: Text(section.title)) {
ForEach(section.occurrences) { occurrence in
NavigationLink(destination: OccurrenceDetail(occurrence: occurrence)) {
OccurrenceRow(occurrence: occurrence)
}
}
}
}
}.navigationBarTitle(Text("Events"))
}
}
}

// These are sample views so that the code will work
struct OccurrenceDetail: View {
let occurrence: Occurrence

var body: some View {
Text(occurrence.title)
}
}

struct OccurrenceRow: View {
let occurrence: Occurrence

var body: some View {
Text(occurrence.title)
}
}

This is the end result.

Nested Views

add and remove list sections using binding value in SwiftUI

I try the code bellow and its work

 List(selection: $selection) {
if self.isEditMode {
Section {
ForEach(self.firstSectionData) { rowData in
MainMenuRowView(rowData: rowData, isEditMode: self.isEditMode)
}
.onMove(perform: { indices, newOffset in
self.groupData.rowsGroup[0].move(fromOffsets: indices, toOffset: newOffset)
})
}
.listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 16))
}


Related Topics



Leave a reply



Submit