// // hackingwithswiftApp.swift // hackingwithswift // // Created by 方君宇 on 2024/9/4. // import SwiftUI import SwiftData @main struct hackingwithswiftApp: App { @State private var container: ModelContainer init() { container = try! ModelContainer(for: Person.self) } var body: some Scene { WindowGroup { ContentView() .modelContainer(container) } } } // // Person.swift // hackingwithswift // // Created by 方君宇 on 2024/11/24. // import Foundation import SwiftData @Model class Person { var name: String var age: Int init(name: String, age: Int) { self.name = name self.age = age } } // // ContenView.swift // hackingwithswift // // Created by 方君宇 on 2024/11/24. // import SwiftUI import SwiftData struct ContentView: View { @Environment(\.modelContext) private var context @Query var adults: [Person] @State private var selectAge: Int = 18 var body: some View { NavigationStack { VStack { // 列表展示查询结果 List { Section("人员名单") { ForEach(adults, id: \.self) { person in Text("\(person.name),年龄:\(person.age)") } } } .frame(height: 330) // 限制列表的高度 VStack { Text("筛选结果页面(比如年龄大于 \(selectAge) 的人员)") Picker("选择年龄", selection: $selectAge) { ForEach(1...100, id: \.self) { age in Text("\(age)").tag(age) } } .pickerStyle(WheelPickerStyle()) NavigationLink(value:selectAge) { Text("查询") .frame(maxWidth: 300) .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(10) } } Spacer() } .navigationTitle("列表") .navigationDestination(for: Int.self) { age in PersonDetailView(age: age) } .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Button("添加测试数据") { try? context.delete(model: Person.self) context.insert(Person(name: "李四", age: 7)) context.insert(Person(name: "章三", age: 58)) context.insert(Person(name: "王五", age: 24)) context.insert(Person(name: "北方", age: 47)) context.insert(Person(name: "卫子夫", age: 15)) context.insert(Person(name: "鸥玉", age: 35)) } } } } } } #Preview { ContentView() .modelContainer(for: Person.self) } // // PersonDetailView.swift // hackingwithswift // // Created by 方君宇 on 2024/11/24. // import SwiftUI import SwiftData struct PersonDetailView: View { @Environment(\.modelContext) private var context @Query var adults: [Person] init(age: Int) { _adults = Query(filter: #Predicate { $0.age > age }) } var body: some View { List(adults) { user in HStack { Text("姓名:\(user.name),") Text("年龄:\(user.age)") } } } } #Preview { PersonDetailView(age:0) .modelContainer(for: Person.self) }