已发布的作品适用于单个对象,但不适用于对象数组

时间:2019-08-01 04:57:12

标签: xcode swiftui xcode11 combine

我正在尝试制作可单独移动的对象。我能够为一个对象成功完成此操作,但是一旦将其放入数组中,这些对象将无法再移动。

型号:

class SocialStore: ObservableObject {
    @Published var socials : [Social]

    init(socials: [Social]){
        self.socials = socials
    }
}

class Social : ObservableObject{
    var id: Int
    var imageName: String
    var companyName: String
    @Published var pos: CGPoint

    init(id: Int, imageName: String, companyName: String, pos: CGPoint) {
        self.id = id
        self.imageName = imageName
        self.companyName = companyName
        self.pos = pos
    }

    var dragGesture : some Gesture {
        DragGesture()
            .onChanged { value in
                self.pos = value.location
                print(self.pos)
        }
    }
}

多张图片(未拖动的图片):

struct ContentView : View {
    @ObservedObject var socialObject: SocialStore = SocialStore(socials: testData)

    @ObservedObject var images: Social = testData[2]

    var body: some View {
        VStack {
            ForEach(socialObject.socials, id: \.id) { social in
                Image(social.imageName)
                    .position(social.pos)
                    .gesture(social.dragGesture)
            }
        }
    }
}

单个图像(图像跟随手势):

struct ContentView : View {
    @ObservedObject var socialObject: SocialStore = SocialStore(socials: testData)

    @ObservedObject var images: Social = testData[2]

    var body: some View {
        VStack {
            Image(images.imageName)
                .position(images.pos)
                .gesture(images.dragGesture)
        }
    }
}

我希望单个物品能够自由移动。我看到坐标正在更新,但是每个图像的位置都没有。

4 个答案:

答案 0 :(得分:5)

首先,免责声明:以下代码并不意味着复制粘贴解决方案。它的唯一目标是帮助您理解挑战。解决问题的方式可能更有效,所以一旦了解问题,就花点时间考虑一下实现。


为什么视图不更新?@Publisher中的SocialStore仅在数组更改时才会发出更新。由于没有从阵列中添加或删除任何内容,因此不会发生任何事情。另外,由于数组元素是对象(而不是值),所以当它们确实改变位置时,数组保持不变,因为对对象的引用保持不变。请记住:类创建对象,结构创建

我们需要一种制作商店的方法,以便在其元素中的某些内容发生更改时发出更改。在下面的示例中,您的商店将订阅其每个元素绑定。现在,您商品的所有已发布更新将被中继到商店发布者,您将获得所需的结果。

import SwiftUI
import Combine

class SocialStore: ObservableObject {
    @Published var socials : [Social]
    var cancellables = [AnyCancellable]()

    init(socials: [Social]){
        self.socials = socials

        self.socials.forEach({
            let c = $0.objectWillChange.sink(receiveValue: { self.objectWillChange.send() })

            // Important: You have to keep the returned value allocated,
            // otherwise the sink subscription gets cancelled
            self.cancellables.append(c)
        })
    }
}

class Social : ObservableObject{
    var id: Int
    var imageName: String
    var companyName: String

    @Published var pos: CGPoint

    init(id: Int, imageName: String, companyName: String, pos: CGPoint) {
        self.id = id
        self.imageName = imageName
        self.companyName = companyName
        self.pos = pos
    }

    var dragGesture : some Gesture {
        DragGesture()
            .onChanged { value in
                self.pos = value.location
                print(self.pos)
        }
    }
}

struct ContentView : View {
    @ObservedObject var socialObject: SocialStore = SocialStore(socials: testData)

    var body: some View {
        VStack {
            ForEach(socialObject.socials, id: \.id) { social in
                Image(social.imageName)
                    .position(social.pos)
                    .gesture(social.dragGesture)
            }
        }
    }
}

答案 1 :(得分:0)

有两种ObservableObject类型,而您感兴趣的是Combine.ObservableObject。它需要类型为objectWillChange的{​​{1}}变量,SwiftUI正是使用该变量来触发新的渲染。我不确定ObservableObjectPublisher的用途是什么,但令人困惑。

Foundation.ObservableObject创建了一个@Published发布者,该发布者可以连接到其他地方的接收器,但是对PassthroughSubject除外的SwiftUI毫无用处。

答案 2 :(得分:0)

您需要实施

let objectWillChange = ObservableObjectPublisher()

在您的ObservableObject类中

答案 3 :(得分:0)

对于那些可能会有所帮助的人。这是@kontiki答案的一种更通用的方法。

这样,您就不必为不同的模型类类型重复自己。

import Foundation
import Combine
import SwiftUI

class ObservableArray<T>: ObservableObject {

    @Published var array:[T] = []
    var cancellables = [AnyCancellable]()

    init(array: [T]) {
        self.array = array

    }

    func observeChildrenChanges<K>(_ type:K.Type) throws ->ObservableArray<T> where K : ObservableObject{
        let array2 = array as! [K]
        array2.forEach({
            let c = $0.objectWillChange.sink(receiveValue: { _ in self.objectWillChange.send() })

            // Important: You have to keep the returned value allocated,
            // otherwise the sink subscription gets cancelled
            self.cancellables.append(c)
        })
        return self
    }

}

class Social : ObservableObject{
    var id: Int
    var imageName: String
    var companyName: String
    @Published var pos: CGPoint

    init(id: Int, imageName: String, companyName: String, pos: CGPoint) {
        self.id = id
        self.imageName = imageName
        self.companyName = companyName
        self.pos = pos
    }

    var dragGesture : some Gesture {
        DragGesture()
            .onChanged { value in
                self.pos = value.location
                print(self.pos)
        }
    }
}

struct ContentView : View {
    //For observing changes to the array only. 
    //No need for model class(in this case Social) to conform to ObservabeObject protocol
    @ObservedObject var socialObject: ObservableArray<Social> = ObservableArray(array: testData)

    //For observing changes to the array and changes inside its children
    //Note: The model class(in this case Social) must conform to ObservableObject protocol
    @ObservedObject var socialObject: ObservableArray<Social> = try! ObservableArray(array: testData).observeChildrenChanges(Social.self)

    var body: some View {
        VStack {
            ForEach(socialObject.array, id: \.id) { social in
                Image(social.imageName)
                    .position(social.pos)
                    .gesture(social.dragGesture)
            }
        }
    }
}