我有一个菜单,用户应该在其中从他们想要包含在例程中的列表中选择练习。这些练习以 LazyVGrid 的形式呈现,弹出一个交互表。此表提供了通过按钮添加该练习的选项。
我想要发生的是在按下按钮时,网格项将从 LazyVGrid 中消失,并且属于自定义类型的练习模型的练习将被附加到选定练习的数组中。
ExerciseModel 类型遵循此模型:
import Foundation
import SwiftUI
struct ExerciseModel: Identifiable, Hashable {
var id = UUID()
var exerciseID: String // ID for the exercise in DB
var userID: String // ID for the user in DB
var username: String // username of user in DB
var exerciseTitle: String
var dateCreate: Date
var exerciseImage: String // where is the image located
var repsInfo: String // How many repetitions for the exercise
var setsInfo: String // How many sets for the exercise
var sharedUserID: String? // ID for the shared user in DB
var sharedUserUsername: String? // Username for the shared user in DB
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
到目前为止,我已经完成了这项工作,从用户选择他们想要包含在例程中的练习的菜单开始(ExerciseView 只是一个包含有关练习信息的 ZStack):
import SwiftUI
struct ExerciseSelectView: View {
@ObservedObject var exercises: ExerciseArrayObject
@State var selectedExercise: ExerciseModel?
@State var selectionArray: [ExerciseModel] = [
]
@State var showSheet: Bool = false
@State var searchText = ""
@Environment(\.presentationMode) var presentationMode
var columns = Array(repeating: GridItem(.flexible()), count: 2)
var body: some View {
NavigationView {
VStack {
SearchBar(text: $searchText)
.padding(.all)
Divider()
ScrollView(.vertical, showsIndicators: false){
LazyVGrid(columns: columns, spacing: 10){
ForEach(exercises.dataArray.filter({"\($0)".contains(searchText) || searchText.isEmpty}), id: \.self) { i in
Button {
selectedExercise = i
showSheet.toggle()
} label: {
ExerciseView(exercise: i)
}
.sheet(item: $selectedExercise) { exercise in
ExerciseDetailAddView(exercise: exercise)
}
}
.listStyle(SidebarListStyle())
.navigationTitle("")
.navigationBarHidden(true)
}
}.padding()
}
}
}
}
作为参考,这是按下网格项目时显示的工作表视图:
import SwiftUI
struct ExerciseDetailAddView: View {
@State var exercise: ExerciseModel
@State var selection: ExerciseModel?
@State var addToggle: Bool = false
var body: some View {
VStack {
ExerciseDetailView(exercise: exercise)
Button(action: {
if addToggle {
} else {
selection = exercise
addToggle.toggle()
print("--> selection: \(selection!)")
}
}, label: {
if addToggle {
Text("Exercise Added".uppercased())
.font(.headline)
.fontWeight(.bold)
.foregroundColor(.white)
.transition(.opacity)
} else {
Text("Add to Routine".uppercased())
.font(.headline)
.fontWeight(.bold)
.foregroundColor(.white)
}
})
.padding()
.frame(width: 300)
.background(addToggle ? Color.green : Color.blue)
.cornerRadius(25)
}
}
}