我想将一些数据从SwiftUI视图保存到模型,以便可以将这些数据用于另一个SwiftUI视图。但是,当我尝试调用Model类并将所有数据作为参数传递时,出现了一些错误。错误提示:
不能在属性初始化程序中使用实例成员'expectedEndDate';属性初始值设定项在“自我”可用之前运行”
这是我的SearchBikeDataModel()代码:
import Foundation
class SearchBikeDataModel: ObservableObject {
@Published var startDate: Date = Date()
@Published var startTime: Date = Date()
@Published var endDate: Date = Date()
@Published var endTime: Date = Date()
@Published var bikeType: String = ""
@Published var collectionPoint: String = ""
@Published var returnPoint: String = ""
init(selectedStartDate: Date, selectedStartTime: Date, selectedEndDate: Date, selectedEndTime: Date, bikeType: String, collectionPoint: String, returnPoint: String) {
self.startDate = selectedStartDate
self.startTime = selectedStartTime
self.endDate = selectedEndDate
self.endTime = selectedEndTime
self.bikeType = bikeType
self.collectionPoint = collectionPoint
self.returnPoint = returnPoint
}
}
这是我尝试将数据作为参数传递的代码:
import SwiftUI
struct BikeSearchFormView: View {
@Binding var isDateTimeShown: Bool
@Binding var isEndDateTimePickerShown: Bool
@State var expectedStartDate = Date()
@State var expectedStartTime = Date()
@State var expectedEndDate = Date()
@State var expectedEndTime = Date()
@State var isBikeTypePickerExpand: Bool = false
@State var isDropOffPointPickerExpand: Bool = false
@State var isPickUpPointPickerExpand: Bool = false
@State var selectedBikeType: String = "BIKE TYPE"
@State var selectedDropOffPoint: String = "DROP OFF POINT"
@State var selectedPickUpPoint: String = "PICKUP POINT"
@State var findBikeError: String = ""
@State var isActive: Bool = false
@ObservedObject var bikeTypeViewModel = VehicleTypeViewModel()
@ObservedObject var findBikeViewModel = FindBikeViewModel()
@ObservedObject var dataModel = SearchBikeDataModel(selectedStartDate: expectedStartDate, selectedStartTime: expectedStartTime, selectedEndDate: expectedEndDate, selectedEndTime: expectedEndTime, bikeType: selectedBikeType, collectionPoint: selectedPickUpPoint, returnPoint: selectedDropOffPoint)
var body: some View {
Text("Hello, World")
}
}
我已经省略了UI代码,因为问题在于我是否遵循正确的方法将数据传递给参数。