Mac*_*kx7 4 core-data edit ios swift swiftui
我正在使用 SwiftUI 学习核心数据。我想制作一个应用程序,我可以在其中发布我喜欢的电影、进行评论并添加评分。
我已经可以在我的应用程序中添加新电影,将其删除,请参阅电影详细信息。现在我想在 CoreData 中编辑我的记录。我发现这很困难,因为我不知道如何将编辑好的电影中的默认值放置到我的表单中。
我的代码:
struct EditMovieVIew: View {
let movie: Movie
@Environment(\.presentationMode) var presentationMode
@Environment(\.managedObjectContext) var moc
@State private var title = ""
@State private var director = ""
@State private var review = ""
@State private var genre = "Fantasy"
@State private var rating = 3
@State private var productionYear = Date()
let genres = ["Sci-Fi","Fantasy", "Comedy", "Horror", "Thriller", "Criminal", "Kids", "Romance", "Drama"]
var body: some View {
NavigationView {
Form {
Section {
TextField("Name of movie", text: $title)
TextField("Director's name", text: $director)
}
Section {
DatePicker(selection: $productionYear, in: ...Date(), displayedComponents: .date) {
Text("Date of production")
}
}
Section {
Picker(selection: $genre, label: Text("Genre")) {
ForEach(genres, id: \.self) {
Text($0).tag($0)
}
}
}.navigationBarTitle("Select your cheese")
Section {
RatingView(rating: $rating)
TextField("Write a review", text: $review)
}
Section {
Button("Save") {
let newMovie = Movie(context: self.moc)
newMovie.title = self.title
newMovie.director = self.director
newMovie.rating = Int16(self.rating)
newMovie.review = self.review
newMovie.genre = self.genre
newMovie.productionYear = Int16(Calendar.current.component(.year, from: self.productionYear))
try? self.moc.save()
self.presentationMode.wrappedValue.dismiss()
}
}
}
.navigationBarTitle("Add Movie")
}
}
}
struct EditMovieVIew_Previews: PreviewProvider {
static let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
static var previews: some View {
let movie = Movie(context: moc)
movie.title = "Test Movie"
movie.director = "Test director"
movie.genre = "Fantasy"
movie.rating = 4
movie.review = "Good movie"
movie.productionYear = 2019
return NavigationView {
EditMovieVIew(movie: movie)
}
}
Run Code Online (Sandbox Code Playgroud)
}
我也试图让
@Binding var movie: Movie
Run Code Online (Sandbox Code Playgroud)
但我的想法都没有奏效。
问题出在哪儿?当我想为我的 TextFields 和 Pickers 分配一个值时,我不能使用我的
文字:$movie.title。//或文本:movie.title //或文本:self.movie.title
所以接下来我想做的是为我的@State 值分配默认值。我已经写了:@State private var title = self.movie.title但Xcode中说,比我不能使用self和movie在这里。
所以我的问题是 - 如何为我的 TextFields 设置默认开始值,以便我能够编辑我的电影并在我的 CoreData 中更新它?
附注。我还有另一个问题。我想制作 DatePicker 仅用于采摘年份。现在我有完整的选择器,然后我只使用用户选择的一年,但我认为只选择一年会更好
您应该在自定义init函数中执行此操作。因为它们被@State包裹起来,所以你需要跳过一个小箍来正确设置它们。
@State private var title: String // don't set up any initial value here
init(movie: Movie) {
self.movie = movie
self._title = State(initialValue: movie.title ?? "")
// etc.
}
Run Code Online (Sandbox Code Playgroud)
请注意_title,这意味着您正在初始化包装器而不是包装值。
对于问题 2,如果您只关心年份,请考虑存储DateComponents而不是Date设置自定义选择器而不是DatePicker. 填充可追溯到 1850 年(或任何时候)的年份数组非常简单。或者有一个年份文本字段。有很多方法可以实现这一点。
| 归档时间: |
|
| 查看次数: |
2388 次 |
| 最近记录: |