出现在操作表中的 SwiftUI 更改状态

问题描述

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

我期望发生的事情: 单击该按钮后,工作表应显示一个随机数 (text)。

会发生什么:第一次,工作表显示 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) 类。在您的情况下 struct view 捕获了初始值。所以使用 ObservableObject 类来引用该值。

这是可能的解决方案。

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)
        })
    }
}