仅在预览模式下出现问题是因为初始化变量之一的方式。 此视图将 PlayerScore 作为参数,因为我需要知道要编辑哪个分数。 它还具有 game 环境对象,其中存储了所有分数。
我做的很简单,我在 PlayerScores 的游戏数组中搜索 playerscore 的索引,以便以后对其进行修改。
预览存在的问题是,我在ScoreEntry_Previews中使用的PlayerScore显然与游戏数组中的playerScore的UUID不匹配。因此它不会呈现预览,因为var初始化失败,因为它找不到UUID。
我该如何处理?
struct ScoreEntry: View {
@EnvironmentObject var game : Game
@Binding var isPresented: Bool
var playerScore: PlayerScore
var scoreIndex: Int {
game.playerScores.firstIndex(where: { $0.id == playerScore.id})!
}
var body: some View {
HStack {
Text("\(self.game.playerScores[self.scoreIndex].totalScore())")
}
}
}
struct ScoreEntry_Previews: PreviewProvider {
static var previews: some View {
ScoreEntry(
isPresented: .constant(true)
,playerScore: PlayerScore(player: Player(name: "SomePlayer", shortName: "Steph", photoURL:"steph", color: .orange),pointsList: [1,2])
).environmentObject(Game())
}
}
struct PlayerScore: Identifiable, Hashable {
var id = UUID()
let player: Player
var pointsList: [Int]
func totalScore() -> Int {
return pointsList.reduce(0, +)
}
mutating func addPoints(scoreValue: Int) {
pointsList.append(scoreValue)
}
}
class Game: ObservableObject {
var players = [Player] ()
@Published var playerScores = [PlayerScore] ()
}
答案 0 :(得分:1)
请勿在内部自动生成id
,而是使其可注入,因此您可以在“预览”中创建一个并在两个位置都注入
struct PlayerScore: Identifiable, Hashable {
var id: UUID // << require external
更新:实际上,以上仍然是可行的方法,但以下是不更改UUID的替代方法。
通过Xcode 11.4 / iOS 13.4测试
经过全面测试的模块代码
struct Player {
var name: String
var shortName: String
var photoURL: String
var color: Color
}
struct PlayerScore: Identifiable {
var id = UUID()
let player: Player
var pointsList: [Int]
func totalScore() -> Int {
return pointsList.reduce(0, +)
}
mutating func addPoints(scoreValue: Int) {
pointsList.append(scoreValue)
}
}
class Game: ObservableObject {
var players: [Player]
@Published var playerScores: [PlayerScore]
init(players: [Player] = [], scores: [PlayerScore] = []) {
self.players = players
self.playerScores = scores
}
}
struct ScoreEntry: View {
@EnvironmentObject var game : Game
@Binding var isPresented: Bool
var playerScore: PlayerScore
var scoreIndex: Int {
game.playerScores.firstIndex(where: { $0.id == playerScore.id})!
}
var body: some View {
HStack {
Text("\(self.game.playerScores[self.scoreIndex].totalScore())")
}
}
}
struct ScoreEntry_Previews: PreviewProvider {
static var previews: some View {
let score = PlayerScore(player: Player(name: "SomePlayer", shortName: "Steph", photoURL:"steph", color: .orange), pointsList: [1, 2])
return ScoreEntry(isPresented: .constant(true), playerScore: score)
.environmentObject(Game(scores: [score]))
}
}