SwiftUI视图不会更新

时间:2019-12-24 06:41:41

标签: ios swift swiftui swift5 combine

当我更改ObservableObject类中的数组中的属性时,我的视图不会更新。我什至声明了一个objectWillChange属性并手动调用了它,但是View只是随机更新,或者不是我想要的那样。我不明白。

import Foundation
import SocketIO
import Combine

class SocketService: ObservableObject {
    static let instance = SocketService()

    let manager = SocketManager(socketURL: URL(RequestURL.base_url)!)
    let socket: SocketIOClient
//    let objectWillChange = ObservableObjectPublisher()

    @Published var allMessages: [Message] = []
//        {
//        willSet {
//            self.objectWillChange.send()
//        }
//    }
    @Published var writtenUsers: [PreviewMessage] = []
//        {
//        willSet {
//            self.objectWillChange.send()
//        }
//    }

    init() {
        socket = manager.defaultSocket
        setSocketEvents()
    }

    // This method is called
    func recieve_read_all_messages() {
        socket.on("recieve-read-all-messages") { (data, ack) in
            guard let arr = data as? [[String: Any]] else { return }
            guard let userID = arr[0]["userID"] as? Int else {
                print("no userID, \(#function), line: \(#line)"); return
            }

            // self.objectWillChange.send()
            for msg in self.allMessages {
                // Here im trying to change the property in the array
                msg.content.readStatus = .read
            }
    }    
}

即使我直接更改此属性,视图也不会更新

@EnvironmentObject private var socketService: SocketService

var body: some View {
    VStack {
         List(filteredMessages, id: \.content.uuid, rowContent: chatSpeechBubbleView)
         sendView
    }
}

private func chatSpeechBubbleView(forMessage message: Message) -> some View {
        ChatSpeechBubble(message: message)
    }

private var sendView: some View {
        Button(action: sendMessage) {
            SFSymbol(.paperplane_fill)
                .fontSize(20)
                .foregroundColor(.white)
                .rotate(.degrees(45))
                .padding(10)
                .padding(.trailing, 5)
                .backgroundColor(.blue)
                .clipCircle()
        }
        .padding(.bottom, 2)
    }

    func sendMessage() {
        for msg in socketService.allMessages {            
            msg.content.readStatus = .read
        }
    }

我应该在何处更新的其他视图:

struct DoubleCheckmark: View {
    var messageContent: MessageContent

    var body: some View {
        HStack(spacing: 0) {
            SFSymbol(.checkmark)
                .resizable()
                .scaledToFit()
            SFSymbol(.checkmark)
                .resizable()
                .scaledToFit()
                .padding(.leading, -9)
        }
        .height(13)
        .foregroundColor(self.messageContent.readStatus == .read ? .blue : .gray)
    }
}
struct ChatSpeechBubble: View {

    // MARK: - init variables
    var message: Message

    // MARK: - normal variables
    var ownSendMessage: Bool {
        message.fromUser.id == UDService.shared.user.id
    }

    // MARK: - Body
    var body: some View {
        messageContent
    }

    private var messageContent: some View {
        HStack(alignment: .bottom) {
            if message.content.text != nil {
                Text(message.content.text!)
                    .foregroundColor(.black)
            }
            if message.content.imageURL != nil {
                Spacer(minLength: 0)
            }
            Text(message.content.timeHourMinute)
                .font(.caption)
                .foregroundColor(.gray)

            if ownSendMessage {
                DoubleCheckmark(messageContent: self.message.content)
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

使用struct,而不是class

问题是Message及其子类型应声明为struct,而不是class。这就是为什么。

这是我用来说明差异的一个基本示例:

  

作为struct的用户:   User as a struct

     

作为class的用户:   User as a class

查看底部的打印日志。使用struct,“正文”会再次打印,为什么?

这是因为类是通过引用传递的,而结构是通过值传递的。这意味着您可以更改类实例的属性,如下所示:

SpriteKit example

如果SKSpriteNode是具有struct属性的let,则尝试更改let常数会出错:

  

Cannot assign to property: '*' is a 'let' constant

结论

因此,由于Messageclass实例不会改变。但是使用struct,整个事情正在改变。您需要更改整个内容(使用struct),以便@PublishedObservableObject可以观察到更改。