My View非常简单:
import SwiftUI
struct CategoryElementView: View {
@Binding var selectedCategory: String?
private let category: String
private let isSelectable: Bool
private var isSelected: Bool {
!isSelectable || category == selectedCategory
}
init(category: String, selectedCategory: Binding<String?>) {
self.category = category
self.isSelectable = true
self._selectedCategory = selectedCategory
}
init(category: String) {
self.category = category
self.isSelectable = false
self._selectedCategory = category
// ❌ Cannot assign value of type 'String' to type 'Binding<String?>'
}
}
我的目的是什么?我需要在2种模式下使用相同的视图:选择它(selectable == true
),只是显示它(selectable == false
)。在没有选择的情况下,不需要从外部绑定。我该怎么做呢?
在构建预览时,想要注入常量值而不是绑定,这是一种非常常见的情况。您应该能够使用相同的方法:
self._selectedCategory = .constant(category)
它应该也适用于nil
。
self._selectedCategory = .constant(nil)
在你的例子中,你甚至可以使用一个构造函数:
init(category: String, selectedCategory: Binding<String?>? = nil) {
self.category = category
self.isSelectable = selectedCategory != nil
self._selectedCategory = selectedCategory ?? .constant(category)
}