3

我将 SwiftUI 用于我的 Mac OS 应用程序。当我通过鼠标单击更改SidebarView中列表的选择(从InboxToday)时,didSet被调用了两次(侧边栏正文也计算了两次)。如果我用箭头(向下|向上)更改选择,则调用一次didSet 。是错误吗?我为我的英语感到抱歉。

双列应用

日志:

  • 用鼠标点击:

willSet = 可选(MiniTodo.NavigationItem.inbox)2021-04-18 00:36:20 +0000

didSet = 可选(MiniTodo.NavigationItem.inbox)2021-04-18 00:36:20 +0000

willSet = 可选(MiniTodo.NavigationItem.inbox)2021-04-18 00:36:20 +0000

didSet = 可选(MiniTodo.NavigationItem.today)2021-04-18 00:36:20 +0000

  • 带箭头:

willSet = 可选(MiniTodo.NavigationItem.inbox)2021-04-18 00:37:11 +0000

didSet = 可选(MiniTodo.NavigationItem.today)2021-04-18 00:37:11 +0000

import SwiftUI

class UIState: ObservableObject {
    
    @Published var navigationItem: NavigationItem? = .inbox {
        didSet {
            print("didSet = \(navigationItem) \(Date())")
        }
        willSet {
            print("willSet = \(navigationItem) \(Date())")
        }
    }
    
}

struct MiniTodoApp: App {
    
    let persistenceController = PersistenceController.shared
    
    @StateObject var uiState: UIState = UIState()

    var body: some Scene {
        WindowGroup {
            NavigationView {
                SidebarView()
                    .environmentObject(uiState)
                //ContentView()
            }
            .navigationViewStyle(DoubleColumnNavigationViewStyle())
            .environment(\.managedObjectContext, persistenceController.container.viewContext)
            
        }
    }
}

struct SidebarView: View {
    
    @Environment(\.managedObjectContext) private var viewContext
    @EnvironmentObject var uiState: UIState
    
    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Folder.name, ascending: true)],
        animation: .default)
    private var folders: FetchedResults<Folder>
    
    var body: some View {
        print("==== Sidebar View ====")
        print(#function)
        print("======================")
        print("")
        return List(selection: $uiState.navigationItem) {
            Group {
                Label("Inbox", systemImage: "tray")
                    .tag(NavigationItem.inbox)
                Label("Today", systemImage: "sun.max.fill")
                    .listItemTint(.yellow)
                    .tag(NavigationItem.today)
                Label("Plan", systemImage: "calendar")
                    .listItemTint(.red)
                    .tag(NavigationItem.plan)
                Label("Completed", systemImage: "checkmark.square.fill")
                    .listItemTint(.green)
                    .tag(NavigationItem.completed)
            }
            
            Section(header:
                        
                        HStack {
                            Text("Lists")
                            Spacer()
                            
                            //if self.onHover {
                            Button {
                                withAnimation {
                                    newFolder()
                                }
                            } label: {
                                Image(systemName: "plus.circle")
                                
                            }
                            .buttonStyle(BorderlessButtonStyle())
                            .padding(EdgeInsets(top: 0.0, leading: 0.0, bottom: 0.0, trailing: 10.0))
                            // }
                            
                        }
            ) {
                ForEach(folders) { folder in
                    FolderRow(folder: folder)
                        .tag(NavigationItem.folder(folder: folder))
                }
            } // Section
            .collapsible(false)
        } // List

        .listStyle(SidebarListStyle())
        .toolbar {
            ToolbarItem(placement: .navigation){
                Button(action: toggleSidebar, label: {
                    Image(systemName: "sidebar.left")
                })
            }
        }
    } // body
    
    // Toggle Sidebar Function
    func toggleSidebar() {
        NSApp.keyWindow?.firstResponder?.tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
    }
    
    func newFolder() {
        withAnimation {
            let newItem = Folder(context: viewContext)
            newItem.name = "It is new folder"
            
            do {
                try viewContext.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }
    
}

4

1 回答 1

0

您可以debounce在 navigationItem 发布者之上使用该功能,您只会收到didSet一次:

class UIState: ObservableObject {

    @Published var navigationItem: NavigationItem? = .inbox
    var cancellable: AnyCancellable?

    init() {
        self.cancellable = $navigationItem.debounce(
            for: .microseconds(1), scheduler: RunLoop.main
        ).sink { _ in
            print("DID SET")
            // Do Whatever you want
        }
    }

}
于 2021-04-18T05:26:39.570 回答