处理 SwiftUI 中的按钮列表

问题描述

我正在开发 SwiftUI 应用程序(Xcode 版本 12.4 和 iOS 14.4.2),但在正确处理列表中的按钮时遇到问题。我希望有人能指出要走的路。

相关代码如下:

struct CustomListView: View {
    var localList:[SomeManagedobject],moc:NSManagedobjectContext
    @State var showingOtherView = false
    @State var selectNbr:Int!
    
    func handleCustomItem(_ argument: SomeManagedobject) {
        print(#function+" (1):\(showingOtherView):")
        selectNbr = localList.firstIndex(of: argument)
        self.showingOtherView.toggle()
        print(#function+" (2):\(showingOtherView):\(selectNbr):")
        ..... Do useful things .....
    }
    
    var body: some View {
        List {
            ForEach(self.localList) {
                item in
                HStack {
                    Spacer()
                    Button(action: {
                        self.handleCustomItem(item)
                    })
                    {
                        Text(item.expression!)
                            .foregroundColor(Color.red))
                            .font(.headline)
                            .padding(.horizontal,11).padding(.vertical,15)
                    }
                    Spacer()
                }
            }
        }.sheet(isPresented: $showingOtherView) {
            OtherView(parameter: localList[selectNbr])
        }
    }
}

当我运行应用程序时,这是我得到的输出,这正是我所期望的:

handleCustomItem(_:) (1):false:
handleCustomItem(_:) (2):true:Optional(4):

然后我在运行这行代码之前有一个断点(以避免崩溃):

OtherView(parameter: localList[selectNbr])

这就是事情变得奇怪的地方(对我来说出乎意料),在调试器中我可以看到:

(lldb) p showingOtherView
(Bool) $R0 = false
(lldb) p selectNbr
(Int?) $R2 = nil
(lldb) 

但我希望 showingOtherViewtrue,并且(更重要的)selectNbr 保持值 4 >.我错过了什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)