[英]Using Bool In Struct in SwiftUI
我在嘗試將 bool 用作 swift 結構的一部分時遇到問題。
struct MapPrefs: Identifiable {
var id = UUID()
var name: String
var isShown: Bool
}
這些首選項的數組由商店提供給 swift-UI 視圖
class MapPrefsStore : ObservableObject {
var willChange = PassthroughSubject<Void, Never>()
@Published var MapPrefs: [MapPrefs] {
didSet { willChange.send(()) }
}
init(mapPrefs: [MapPrefs]) {
self.MapPrefs = mapPrefs
}
}
設置視圖觀察存儲並將數組傳遞給單元格視圖
struct SettingsView: View {
@ObservedObject var mapPrefsStore = MapPrefsStore(mapPrefs: MapPrefsTestData)
var body: some View {
NavigationView {
List {
Section(header: Text("Map Preferences"), footer: Text("")) {
ForEach(mapPrefsStore.MapPrefs) { mapPrefs in
MapPrefsCell(mapPrefs: mapPrefs)
}
.onMove(perform: moveMap)
}
.background(Color.clear)
}
.navigationBarTitle(Text("Settings"))
.navigationBarItems(trailing: EditButton())
.listStyle(GroupedListStyle())
}
}
func moveMap(from source: IndexSet, to destination: Int) {
guard let sourceIndex = Array(source).first else { return }
mapPrefsStore.MapPrefs.insert(mapPrefsStore.MapPrefs.remove(at: sourceIndex), at: destination)
}
}
struct MapPrefsCell : View {
let mapPrefs: MapPrefs
var body: some View {
Toggle(isOn: mapPrefs.isShown) {
Text(mapPrefs.name)
}
}
}
}
這給了我以下錯誤
Cannot convert value of type 'Bool' to expected argument type 'Binding<Bool>'
我不知道如何允許被調用的 function (MapPrefsCell) 能夠訪問 isShown 屬性。 我嘗試了添加 $ 符號的各種組合。
isShown 被聲明為 Bool。 用$
傳遞它是行不通的,因為你不能將它轉換為Binding<Bool>
。
您可以在結構中將其聲明為@State
:
struct MapPrefs: Identifiable {
var id = UUID()
var name: String
@State var isShown: Bool
}
然后將其作為綁定傳遞...
Toggle(isOn: mapPrefs.$isShown) {
Text(mapPrefs.name)
}
編輯:
您還可以創建自定義 State 並將 mapPrefs 的值用於該 State。 但是之后您需要將更改存儲到 object 中。 在這種情況下,您不需要將其聲明為 @State
struct MapPrefs: Identifiable {
var id = UUID()
var name: String
var isShown: Bool
}
struct MapPrefsCell : View {
let mapPrefs: MapPrefs
@State var toggle : Bool
init(mapPrefs: MapPrefs)
{
//create State with initial value here
self._toggle = State(initialValue: self.mapPrefs.isShown)
}
var body: some View {
Toggle(isOn: $toggle) {
Text(mapPrefs.name)
}
}
}
上面的答案部分有效,但因為我與其他視圖共享這些設置,所以我需要能夠在切換更改時讀取和寫入,所以我將結構轉換為 class
這是我所做的,以便其他人可以受益。
import SwiftUI
import Combine
class MapPrefs: Identifiable, ObservableObject {
var willChange = PassthroughSubject<Void, Never>()
var id = UUID()
@Published var name: String = "" {didSet { willChange.send(()) }}
@Published var isShown: Bool = false {didSet { willChange.send(()) }}
init (name: String , isShown: Bool) {
//self.id = UUID()
self.name = name
self.isShown = isShown
}
}
然后在創建視圖時,我可以訪問該屬性並且切換工作
struct MapPrefsCell : View {
@ObservedObject var mapPrefs: MapPrefs
var body: some View {
Toggle(isOn: $mapPrefs.isShown ) {
Text(mapPrefs.name)
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.