首页 > 解决方案 > macOS SwiftUI 文本字段在失去焦点后被删除

问题描述

我有一个奇怪的问题,即在选择另一个文本字段后文本字段被删除。

我有一个EnvironmentObject

func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Create the SwiftUI view that provides the window contents.
        let shellInteractor = ShellInteractor()
        let contentView = ContentView().environmentObject(shellInteractor)
}

注入视图

struct ContentView: View {
    @EnvironmentObject var shellInteractor: ShellInteractor

    var body: some View {
        ScrollView {
            VStack {
                HStack {
                    Text("Enter target bundle identifier:")
                    TextField("com.mycompany.app", text: $shellInteractor.bundleId)
                }.padding()
                HStack {
                    Text("Enter icon badge count:")
                    TextField("0", text: $shellInteractor.badgeNumber)
                }.padding()
                HStack {
                    Text("Enter message identifier:")
                    TextField("ABCDEFGHIJ", text: $shellInteractor.messageId)
                }.padding()

                Text("Found Running Sim: ")
                Text(self.shellInteractor.shellOutput).fontWeight(.semibold)
                Button(action: {
                    self.shellInteractor.sendNotification()
                }) {
                    Text("SEND!!!")
                    .fontWeight(.semibold)
                }.padding()
            }.padding()
        }
    }
}
class ShellInteractor: ObservableObject {
    @Published var shellOutput: String = ""

    public var badgeNumber: String = ""
    public var messageId: String = ""
    public var bundleId: String = ""
}

正如我所说,当我在任何文本字段中输入文本并选择另一个文本字段或点击TAB键(基本上是在失去焦点时)时,文本字段会删除文本并再次显示占位符。

标签: macosswiftuitextfieldcombine

解决方案


更新你的模型

class ShellInteractor: ObservableObject {
    @Published var shellOutput: String = ""

    @Published var badgeNumber: String = ""
    @Published var messageId: String = ""
    @Published var bundleId: String = ""
}

推荐阅读