【问题标题】:macOS SwiftUI Textfield gets deleted after losing focusmacOS SwiftUI 文本字段在失去焦点后被删除
【发布时间】:2020-05-26 05:02:11
【问题描述】:

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

我有一个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 键(基本上是在失去焦点时)时,文本字段会删除文本并再次显示占位符。

【问题讨论】:

    标签: macos swiftui textfield combine


    【解决方案1】:

    更新你的模型

    class ShellInteractor: ObservableObject {
        @Published var shellOutput: String = ""
    
        @Published var badgeNumber: String = ""
        @Published var messageId: String = ""
        @Published var bundleId: String = ""
    }
    

    【讨论】:

    • 非常感谢,就是这样!
    • @AlexBartiş 不幸的是,这样的事情必须被编译器识别。顺便说一句,这是一种解决方法,您的代码就像在 iOS 上编写的那样工作
    • 是的,有道理。
    猜你喜欢
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 2020-03-18
    • 2020-05-06
    • 1970-01-01
    相关资源
    最近更新 更多