背景: 我正在使用核心数据来处理我的应用程序用户设置的持久存储。我的设置之一是
Color
值,我将其转换为 RGB 值,存储为由 Core Data 管理的 InitialsImageColor
类型对象的属性。在Color
视图中使用ColorPicker
选择Form
。
问题: 我有一个变量
imageColor
,我正在视图的init()
声明中初始化它。编译器抛出错误“初始化前使用的变量‘self.imageColor’”5 次。为了清楚起见,这是带有注释的相关代码部分:
struct SettingsView: View {
// Access the managed object context for saving changes to Core Data
@Environment(\.managedObjectContext) var moc
// Load stored InitialsImageColor objects from Core Data
@FetchRequest(sortDescriptors: []) var colorSetting: FetchedResults<InitialsImageColor>
// A Color variable for the ColorPicker View to bind to
@State private var imageColor: Color
// A String variable for the Form View's .searchable modifier to bind to
@State private var searchText: String = ""
// A Bool variable to change to make the .sheet containing SettingsView to disappear
@Binding var showSettings: Bool
// An initializer to set the starting value for the ColorPicker View to use
init() {
imageColor = Color( // This line throws error
red: colorSetting.first?.r ?? 255.0, // This line throws error
green: colorSetting.first?.g ?? 255.0, // This line throws error
blue: colorSetting.first?.b ?? 255.0, // This line throws error
opacity: colorSetting.first?.a ?? 1.0 // This line throws error
)
}
最初,我试图在它的声明中初始化
imageColor
,但是当然这没有用,因为它使用另一个变量来得出它的值并且范围在视图的body
之外。我把它放在init()
声明中来解决那个问题,然后就发生了。