Home > database >  TextField in SwiftUI resets after every keystroke
TextField in SwiftUI resets after every keystroke

Time:12-15

in this script the TextField is shown, but it resets to "player 1" after every keystroke. Can anyone help me?

import SwiftUI

class Player: ObservableObject {
    @Published var playerData = "player 1"
}

let player = Player()

struct ContentView: View {
    @ObservedObject var player: Player
    
    var body: some View {
        TextField("player", text: $player.playerData)
    }  
}

Tried with other code, but without success.

CodePudding user response:

class Player: ObservableObject {
    @Published var playerData = "player 1"
    
    static let shared = Player()
}

struct ContentView: View {
    @ObservedObject var player = Player.shared
    
    var body: some View {
        TextField("player", text: $player.playerData)
    }
}

However, usually the model store would be an environmentObject PlayerStore and would contain an array of Player model structs.

CodePudding user response:

Replace @ObservedObject with @StateObject and it should work

  • Related