SwiftUI中的TextField在每次击键后重置

yhived7q  于 2022-12-17  发布在  Swift
关注(0)|答案(2)|浏览(125)

在这个脚本中显示了文本域,但是每次击键后它都重置为“播放器1”。2有人能帮助我吗?

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

已尝试使用其他代码,但未成功。

ryevplcw

ryevplcw1#

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

但是,通常模型存储是environmentObjectPlayerStore,并且包含Player模型结构体数组。

q35jwt9p

q35jwt9p2#

将@ObservedObject替换为@StateObject,它应该可以工作

相关问题