我希望能够在网格中选择多个项目(例如,前20个)并更改元素的颜色。
import SwiftUI
struct ContentView: View {
@State var showView = false
@State private var birthDate = Date.now
struct Day: Identifiable {
let id = UUID()
let value: Int
}
struct Month {
let name: String
let numberOfDays: Int
var days: [Day]
init(name: String, numberOfDays: Int) {
self.name = name
self.numberOfDays = numberOfDays
self.days = []
for n in 1...numberOfDays {
self.days.append(Day(value: n))
}
}
}
let year = [
Month(name: "Youth", numberOfDays: 12),
Month(name: "Teenager", numberOfDays: 7),
Month(name: "20s - 30s", numberOfDays: 20),
Month(name: "Middle ages", numberOfDays: 26),
Month(name: "Retirement", numberOfDays: 35),
]
let layout = [
GridItem(.flexible(minimum: 40)),
GridItem(.flexible(minimum: 40)),
GridItem(.flexible(minimum: 40)),
GridItem(.flexible(minimum: 40)),
GridItem(.flexible(minimum: 40)),
]
var body: some View {
VStack {
DatePicker(selection: $birthDate, in: ...Date.now, displayedComponents: .date) {
}
Text("Your Birthdate is \(birthDate.formatted(date: .long, time: .omitted))")
ScrollView {
LazyVGrid(columns: layout, pinnedViews: [.sectionHeaders]) {
ForEach(year, id: \.name){ month in
Section(header: Text(verbatim: month.name).font(.headline)) {
ForEach(month.days) { day in
Capsule()
}
}
}
}.padding(5)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
看起来是这样的。
screenshot of the app currently
这就是我想要发生的-我会整合日期,但需要一种方法来更改特定数量的日期(在本例中,其中7个日期已更改:
same screenshot with 7 elements selected and changed colour from blue to black
我已经尝试了ForEach,但似乎不能得到它的工作,任何帮助将不胜感激。
2条答案
按热度按时间hfsqlsce1#
希望这能有所帮助):
monwx1rj2#
1.你需要在你的
Day
结构体中添加一个新的属性来跟踪选择,我称之为selected
。1.必须将
year
声明为@State变量-因此它是视图的真实来源,并且可以修改。1.要使
day
在视图中可变,必须使用ForEach
的$初始化器向下传递年、月和日。(通过为基本数据使用ObservableObject类,可以更好地求解2.和3.)
1.根据
day.selected
变更胶囊颜色。1.点击手势切换
day.selected
。