I have a SwiftUI question which doesn't look like it's answered or a duplicate of another issue, and SwiftUI is rather new.
The following code, with my understanding, show toggle the background of the Button control. The number of likes increments as expected, but the state changes don't seem to pass through to the Book struct.
Everything I have read is that in the preview, you need to use:
.constant(x) within the view of the PreviewProvider.
However, it doesn't work and the Button with likes does not the foreground, nor the background color.
When debugging the app, the result of the book isLiked does change. But the foreground/background colors do not.
Here is the code for the view.
import SwiftUI
struct BookDetailView: View {
@Binding var book: Book
@State var likes: Int = 0
var body: some View {
VStack {
Text(book.title)
Image(book.imageName)
.resizable()
.aspectRatio(contentMode: .fit)
.scaledToFit()
Button(action: {
self.book.isLiked.toggle()
self.likes = self.likes + 1
}) {
Text(" Like \(likes)")
.padding()
.foregroundColor(self.book.isLiked ? .secondary : .primary)
.background(self.book.isLiked ? Color.rayWenderlichGreen : Color.white)
.cornerRadius(10)
}
}
}
}
struct BookDetailView_Previews: PreviewProvider {
static var previews: some View {
BookDetailView(book: .constant(Book.demoBooks.randomElement()!))
}
}
Here is the actual book model
import SwiftUI
struct Book: Identifiable {
var id = UUID()
var title: String
var imageName: String
var isLiked = false
}
extension Book: Equatable {
static func == (lhs: Book, rhs: Book) -> Bool {
return lhs.id == rhs.id
}
}
I have invested some time in trying to understand why this is happening, and it seems like it could just be a bug with SwiftUI.
Any thoughts or suggestions?