以防萬一, Book 結構如下。
struct Book: Identifiable {
var id = UUID().uuidString
var title: String
var description: String
var imageURL: URL
var sourceOfDesc: String
var descSourceCitation: String
}
我的目標是顯示標記為收藏夾的 BookDetailView 串列。已經創建了一個從收藏夾中添加和洗掉書籍的類。
class Favorites: ObservableObject {
// The actual books the user marked as favorite.
@Published var books: [String]
// The key to be used to read/write in the UserDefaults
private let saveKey = "Favorites"
init() {
// Load saved data
books = []
}
// Returns true if the set contains this book
func contains(_ book: Book) -> Bool {
books.contains(book.id)
}
func add(_ book: Book) {
objectWillChange.send()
books.insert(book.id, at: 0)
save()
}
func remove(_ book: Book) {
objectWillChange.send()
books.removeAll { $0 == book.id }
save()
}
func save() {
// Write data
}
}
更新了下面的收藏夾視圖。
struct FavoritesView: View {
@ObservedObject var favoriteList: Favorites
var book: Book
var body: some View {
List(favoriteList.books) { book in
NavigationLink {
WorksListTemplateView(books: book)
} label: {
Text(book.title)
}
}
}
}
我在收藏夾視圖上收到多條錯誤訊息,跳出來給我的是這些 2:
無法將型別“[String]”的值轉換為預期的引數型別“Binding”
無法推斷通用引數“資料”
uj5u.com熱心網友回復:
List
除了 a RandomAccessCollection
,Set
不符合它。所以你應該將你的集合轉換為一個陣列:Array(favoritesList.books)
。
但是,由于String
不符合Identifiable
,還需要在串列中添加一個 id :
List(Array(favoritesList.books), id: \.self) { book in
備注:
正如評論中提到的,
Favorites
你應該標記書籍使用@Published
才能ObservableObject
生效:@Published var books: Set<String> //or an array [String]
在
FavoritesView
中, favoriteList 應該是:@ObservedObject var favoriteList: Favorites //ObservedObject & not StateObject because the object is passed //down from another View & not directly initialized in the View.
在
BookDetailView
,你不需要.environmentObject(favorites)
。您在第一次初始化它時注入它,即在您沒有的地方@EnvironmentObject var favorites: Favorites
或當您展示另一個View
需要它的地方時。同樣在
BookDetailView
,如果你需要改變 book 從它的View
標記中使用@State
. 如果您需要從另一本書中變異View
,請在其中View
標記它@Binding
。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/508548.html
上一篇:如果設定了ItemContainerStyle,UWPListView所選專案突出顯示消失
下一篇:顯示解析度更改后的表單重繪問題