こんにちは。
ファイル間で共有する構造体を作りたいです。
@EnvironmentObjectというものを知り、実際に使ってみたのですが、エラーが2つ出てしまい。うまくいきません。
//Argument passed to call that takes no arguments //Generic struct 'EnvironmentObject' requires that '[Items]' conform to 'ObservableObject'
原因と解決策をご教授願いたいです。
Swift
1import SwiftUI 2 3// 構造体を定義 4class Items: ObservableObject, Identifiable { 5 var id: String { 6 return name 7 } 8 @Published var name: String 9 @Published var color: Color 10 11 init(name: String, color: Color) { 12 self.name = name 13 self.color = color 14 } 15} 16 17struct ContentView: View { 18 // 構造体の中身を決めて、配列化する 19 @EnvironmentObject var items: [Items] = [ 20 //Argument passed to call that takes no arguments 21 //Generic struct 'EnvironmentObject' requires that '[Items]' conform to 'ObservableObject' 22 Items(name: "Apple", color: .red), 23 Items(name: "Orange", color: .orange), 24 Items(name: "Banana", color: .yellow), 25 ] 26 27 28 var body: some View { 29 VStack { 30 // 構造体をリスト(ボタン)化する 31 ForEach(items) { item in 32 Button(action: { 33 print(item) 34 35 }) { 36 HStack { 37 Text(item.name) 38 Spacer() 39 Image(systemName: "plus") 40 } 41 .frame(width: 320, height: 30, alignment: .leading) 42 .padding() 43 .foregroundColor(.white) 44 .background(item.color) 45 .cornerRadius(5) 46 } 47 } 48 } 49 } 50}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/03/16 01:31