动作中出现的 SwiftUI 更改状态 sheet

SwiftUI changing state that appears in action sheet

我有一个简单的 SwiftUI 示例,它没有按预期运行。

我期望发生的事情: 单击按钮时,sheet 应显示一个随机数 (text)。

发生了什么:第一次,sheet 显示 foo。在随后的时间里,会出现一个数字。

为什么第一次没有出现数字?


ContentView.swift

import SwiftUI

struct ContentView: View {
    @State var showSheet = false
    @State var text = "foo"


    var body: some View {
        VStack {
            Text("Hello")
            PillButton(title: "Start Test", action: {
                print("Button tapped")
            }, text: $text, showSheet: $showSheet)
        }.sheet(isPresented: $showSheet, content: {
            Text(text)
        })
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

PillButton.swift

import SwiftUI

struct PillButton: UIViewRepresentable {
    let title: String
    let action: () -> ()
    @Binding var text: String
    @Binding var showSheet: Bool

    var pillButton = UIButton()

    func makeCoordinator() -> Coordinator { Coordinator(self) }

    class Coordinator: NSObject {
        var parent: PillButton

        init(_ pillButton: PillButton) {
            self.parent = pillButton
            super.init()
        }

        @objc func doAction(_ sender: Any) {
            let number = Int.random(in: 0..<100)
            self.parent.text = String(number)
            self.parent.action()
            self.parent.showSheet = true
        }
    }

    func makeUIView(context: Context) -> UIButton {
        let button = UIButton(type: .system)
        button.setTitle(self.title, for: .normal)
        button.addTarget(context.coordinator, action: #selector(Coordinator.doAction(_ :)), for: .touchDown)
        return button
    }

    func updateUIView(_ uiView: UIButton, context: Context) {}
}

使用 ViewModel (ObservableObject)class。在您的情况下,结构视图捕获了初始值。所以使用 ObservableObject class 来引用值。

这是可能的解决方案。

class ContentViewModel: ObservableObject{
    @Published var text = "foo"
}
struct ContentView: View {
    @State var showSheet = false
    @ObservedObject var viewModel = ContentViewModel()
    
    var body: some View {
        VStack {
            Text("Hello")
            PillButton(title: "Start Test", action: {
                print("Button tapped")
            }, text: $viewModel.text, showSheet: $showSheet)
        }.sheet(isPresented: $showSheet, content: {
            Text(self.viewModel.text)
        })
    }
}