簡體   English   中英

SwiftUI 綁定到數組中的@ObservableObject

[英]SwiftUI Bind to @ObservableObject in array

如何將可綁定的 object 傳遞到 ForEach 循環內的視圖中?

下面的最小可重現代碼。

class Person: Identifiable, ObservableObject {
    let id: UUID = UUID()
    @Published var healthy: Bool = true
}


class GroupOfPeople {
    let people: [Person] = [Person(), Person(), Person()]
}

public struct GroupListView: View {
    
    //MARK: Environment and StateObject properties
    
    //MARK: State and Binding properties
    
    //MARK: Other properties
    let group: GroupOfPeople = GroupOfPeople()
    
    //MARK: Body
    public var body: some View {
        ForEach(group.people) { person in
            //ERROR: Cannot find '$person' in scope
            PersonView(person: $person)
        }
    }
    
    //MARK: Init
    
}

public struct PersonView: View {
    
    //MARK: Environment and StateObject properties
    
    //MARK: State and Binding properties
    @Binding var person: Person
    //MARK: Other properties
    
    
    //MARK: Body
    public var body: some View {
        switch person.healthy {
        case true:
            Text("Healthy")
        case false:
            Text("Not Healthy")
        }
    }
    
    //MARK: Init
    init(person: Binding<Person>) {
        self._person = person
    }
}

我得到的錯誤是Cannot find '$person' in scope 我知道在執行 ForEach 循環時,變量的 @Binding 部分不在 scope 中。 我正在尋找關於不同模式的建議,以完成 @Binding 對象到 SwiftUI 列表中的視圖。

SwiftUI 方式是這樣的:

// struct instead of class
struct Person: Identifiable {
    let id: UUID = UUID()
    var healthy: Bool = true
}


// class publishing an array of Person
class GroupOfPeople: ObservableObject {
    @Published var people: [Person] = [
        Person(), Person(), Person()
    ]
}

struct GroupListView: View {
    
    // instantiating the class
    @StateObject var group: GroupOfPeople = GroupOfPeople()
    
    var body: some View {
        List {
            // now you can use the $ init of ForEach
            ForEach($group.people) { $person in
                PersonView(person: $person)
            }
        }
    }
}

struct PersonView: View {
    
    @Binding var person: Person

    var body: some View {
        HStack {
            // ternary instead of switch
            Text(person.healthy ? "Healthy" : "Not Healthy")
            Spacer()
            // Button to change, so Binding makes some sense :)
            Button("change") {
                person.healthy.toggle()
            }
        }
    }
}

你不需要Binding 你需要ObservedObject

對於仍然想知道的人......看起來已經添加了

.onContinuousHover(perform: { phase in
    switch phase {
    case .active(let location):
        print(location.x)
    case .ended:
        print("ended")
    }
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM