I created a view showing a list of Button. These buttons are displaying a date. This view is instantiated in my HomeView.
My need is that whenever the user taps one of the button, the date displayed by the tapped button is stored to a variable. Only one button should be selected at a time.
My list of buttons looks like this.
Day.swift
struct Day: View
{ var date: Date @State private var isSelected = false func updateIsSelected()
{ if (isSelected == true)
{
isSelected = false
}
else
{
isSelected = true
}
} var body: some View { VStack { Button("\(date.formatted(Date.FormatStyle().day(.twoDigits).month(.twoDigits)))", action: { updateIsSelected() }) }.buttonStyle(.bordered) }
}
DaysPanel.swift
struct DaysPanel: View
{
var currentDate: Date = User.shared.startDate
var dayList: [Day] = []
init(_ nbWeeks: Int)
{
for _ in 1 ... nbWeeks
{ addOneWeek() }
}
mutating func addOneDay()
{ // Populate the list of Day
let tmpDay = Day(date: currentDate) dayList.append(tmpDay)
// Increase the date by a day
currentDate = currentDate.addingTimeInterval(Double(SECONDS_IN_DAY))
} mutating func addOneWeek()
{ for _ in 1 ... DAYS_IN_WEEK { addOneDay() }
}
var body: some View
{
VStack
{
HStack
{ Spacer() ScrollView(.horizontal) { HStack { ForEach(0 ..< dayList.count) { index in dayList[index] } } } }
}
}
}
I though I could implement a getter method for my Day to retrieve it's status. Then, from the DayPanel, I could have iterated over the dayList and check which one is selected and retrieve it's date. For some reason, my HomeView is not letting me do so, nothing happens when I tap one of the day button.
HomeView.swift
var body: some View
{
VStack
{
self.dayPanel.onTapGesture
{
// Method here to iterate over panel list and retrieve selected button and its value
}
}
}