当我通过鼠标单击更改 SwiftUI 列表的选择时,@Published 属性的 didSet 被调用了两次

Posted

技术标签:

【中文标题】当我通过鼠标单击更改 SwiftUI 列表的选择时,@Published 属性的 didSet 被调用了两次【英文标题】:When I change selection of the SwiftUI List with mouse click didSet of the @Published property is called twice 【发布时间】:2021-04-18 00:32:47 【问题描述】:

我将 SwiftUI 用于我的 Mac OS 应用程序。当我通过鼠标单击 didSet 在 SidebarView 中更改 List 的选择(从 InboxToday 被调用两次(侧边栏正文也被计算两次)。如果我用箭头(向下|向上)更改选择 didSet 会被调用一次。是错误吗?对不起我的英语。

DoubleColumn App

日志:

用鼠标点击:

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

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

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

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

带箭头:

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

didSet = Optional(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)")
            
        
    
    


【问题讨论】:

【参考方案1】:

您可以在 navigationItem 发布者之上使用debounce 函数,并且您只会收到一次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
        
    


【讨论】:

以上是关于当我通过鼠标单击更改 SwiftUI 列表的选择时,@Published 属性的 didSet 被调用了两次的主要内容,如果未能解决你的问题,请参考以下文章

SwiftUI - 如何在点击时更改按钮的图像?

通过单击变体图像 Woocommerce 更改产品变体

SwiftUI 列表内容通过选择重置

为啥单击 SwiftUI 中的列表项后列表视图项变为灰色?

状态更改时自定义 SwiftUI 视图不会更新

在 OpenGL 上单击鼠标时无法旋转和更改对象的颜色