温馨提示:本文最后更新于
2025-06-05 10:34:56
,某些文章具有时效性,若有错误或已失效,请在下方留言。基于模型扩展
在模型的基础上进行扩展,这里以 movie
模型为例
import Foundation
import SwiftData
@Model
final class Movie {
var title: String
var year: Int
@Relationship(deleteRule: .cascade, inverse: \Review.movie) var reviews: [Review]? = []
init(title: String, year: Int) {
self.title = title
self.year = year
}
}
// MARK: - 预览的示例数据
extension Movie {
@MainActor
static var preview: ModelContainer {
let container = try! ModelContainer(for: Movie.self, configurations: ModelConfiguration(isStoredInMemoryOnly: true))
container.mainContext.insert(Movie(title: "The Shawshank Redemption", year: 1994))
container.mainContext.insert(Movie(title: "The Godfather", year: 1972))
container.mainContext.insert(Movie(title: "The Godfather: Part II", year: 1974))
container.mainContext.insert(Movie(title: "The Dark Knight", year: 2008))
return container
}
}
具体的使用,如下
#Preview {
NavigationStack {
MovieListScreen()
.modelContainer(Movie.preview)
}
}
直接页面
SwiftData 相关的视图页面中 Preview
的处理:
- 创建自定义
ModelConfiguration
对象以指定我们想要的内存存储。
- 创建自定义
- 使用它来创建一个模型容器
ModelContainer
。
- 使用它来创建一个模型容器
- 创建示例对象
- 将示例对象和模型容器发送到视图页面
以下是具体的代码处理
#Preview {
// 创建自定义 `ModelConfiguration` 对象以指定我们想要的内存存储。使用它来创建一个模型容器 `ModelContainer`
let container = try! ModelContainer(for: Movie.self, configurations: ModelConfiguration(isStoredInMemoryOnly: true))
// 创建示例对象
container.mainContext.insert(Movie(title: "The Shawshank Redemption", year: 1994))
container.mainContext.insert(Movie(title: "The Godfather", year: 1972))
container.mainContext.insert(Movie(title: "The Godfather: Part II", year: 1974))
container.mainContext.insert(Movie(title: "The Dark Knight", year: 2008))
// 将示例对象和模型容器发送到视图页面
return NavigationStack {
MovieListScreen()
.modelContainer(container)
}
}
如果您尝试创建 SwiftData 模型的实例,但还没有模型容器,则预览将崩溃。
子视图传入 Model
在子视图中传图模型数据,这里以 ParkModel
为例。
import SwiftUI
import SwiftData
struct ParkRowView: View {
let park: ParkModel
var body: some View {
HStack {
Image(uiImage: park.viewImage)
.resizable()
.scaledToFit()
.frame(height: 60)
.clipShape(.rect(cornerRadius: 8))
VStack(alignment: .leading) {
Text(park.name)
.font(.title)
Text(park.viewLocation)
.fontWeight(.light)
}
Spacer()
}
}
}
#Preview {
let container = try! ModelContainer(for: ParkModel.self, configurations: ModelConfiguration(isStoredInMemoryOnly: true))
let park = ParkModel(
name: "Arches",
image: UIImage(resource: .arches).pngData()!,
region: "Utah",
country: "United States",
rating: 6
)
container.mainContext.insert(park)
return ParkRowView(park: park)
.modelContainer(container)
}
Ai创建 Mock 数据
![图片[1]-如何在 SwiftUI 预览中使用 SwiftData-Stewed Noodles 资源](https://img.stewednoodles.com/images/2025/01/22/StewedNoodles20250122121821.webp)
© 版权声明
THE END
暂无评论内容