【发布时间】:2019-12-10 17:36:35
【问题描述】:
我是一位经验丰富的 iOS 开发人员,但对 SwiftUI 不熟悉。我正在尝试创建一个由数据模型支持的动态接口。以下说明了我正在尝试做的事情:
模型对象:
class Book : Hashable {
static func == (lhs: Book, rhs: Book) -> Bool {
return lhs.title == rhs.title && lhs.author == rhs.author && lhs.favorite == rhs.favorite
}
var title : String
var author : String
var favorite : Bool = false
init(title : String, author: String) {
self.title = title
self.author = author
}
func hash(into hasher: inout Hasher) {
hasher.combine(title)
hasher.combine(author)
hasher.combine(favorite)
}
}
内容视图:
struct ContentView: View {
@State private var library = [
Book(title: "Lord of The Rings", author: "J.R.R. Tolkien"),
Book(title: "Harry Potter", author: "J.K. Rowling"),
Book(title: "Under the Dome", author: "Steven King")
]
var body: some View {
NavigationView {
MasterView(books: $library)
.navigationBarTitle(Text("Library"))
}.navigationViewStyle(DoubleColumnNavigationViewStyle())
}
}
struct MasterView: View {
@Binding var books: [Book]
var body: some View {
List {
ForEach(books, id: \.self) { book in
HStack {
Button(action: {}, label: {
(book.favorite ?
Image(systemName: "heart.fill") :
Image(systemName: "heart"))
.imageScale(.large)
}).onTapGesture {
book.favorite.toggle()
}
Text("\(book.title) by \(book.author)")
}
}
}
}
}
结果如下:
外观正确。但是,我希望 like 按钮能够工作:我希望点击更新模型对象中的收藏变量,然后按钮本身应该相应地更改。
第一个发生,第二个没有。
我做错了什么,如何获得我想要的动态 UI 更新?
【问题讨论】:
标签: ios swift user-interface mvvm swiftui