微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

处理 SwiftUI 中的按钮列表

如何解决处理 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 举报,一经查实,本站将立刻删除。