When I using ForEach, Xcode gave the error like the title said. Here is the code:
//SuggestBooksRow
import SwiftUI
struct SuggestBooksRow: View {
var items: [Book]
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top, spacing: 0) {
ForEach(items) { book in
Text(book.name)
}
}
}
}
}
struct SuggestBooksRow_Previews: PreviewProvider {
var books: [Book] = [
Book(name: "EvanLuo42", imageName: "book1"),
Book(name: "EvanLuo42", imageName: "book1")
]
static var previews: some View {
SuggestBooksRow(items: books)
}
}
And other codes:
//SuggestBookItem
import SwiftUI
struct SuggestBooksItem: View {
var book: Book
var body: some View {
VStack(alignment: .leading) {
book.image
.resizable()
.frame(width: 155, height: 155)
.cornerRadius(5)
Text(book.name)
.font(.caption)
}
.padding(.leading, 15)
}
}
The model of the Books:
//Book
import Foundation
import SwiftUI
struct Book: Hashable, Codable {
var name: String
var imageName: String
var image: Image {
Image(imageName)
}
}