我一直在跟随斯坦福大学的SwiftUI课程,现在我已经到了一个地步,我可以百分之百确定我的代码基本上与我所跟随的代码相同,但它却不能正常工作。我一直在尝试调试它,但由于某些我不理解的原因,视图没有更新。
视图模型:
class CardModel: ObservableObject
{
// view model
static var items = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",]
static var count = 3
static func createMemoryGame() -> MemoryGame<String>
{
MemoryGame<String>(numberOfPairsOfCards: CardModel.count, createCardContent:
{
pairIndex in
CardModel.items[pairIndex]
})
}
@Published private var model: MemoryGame<String> = CardModel.createMemoryGame()
var cards: Array<MemoryGame<String>.Card>
{
return model.cards
}
// MARKS: - Intent(s)
func choose(_ card: MemoryGame<String>.Card)
{
print("debug func choose in cardmodel")
model.choose(card)
}
}
视图:
struct ContentView: View{
@ObservedObject var viewModel: CardModel
var body: some View
{
VStack
{
LazyVGrid(columns: [GridItem(.adaptive(minimum: 75))])
{
ForEach(viewModel.cards)
{
card in
CardView(card: card).aspectRatio(2/3, contentMode: .fit)
.onTapGesture {
print("\(card.isFaceUp)")
viewModel.choose(card)
print("\(card.isFaceUp)")
}
}
}
Spacer()
.foregroundColor(.red)
}
.padding(.horizontal)
.font(.largeTitle)
}
}
模型:
struct MemoryGame<CardContent>
{
private(set) var cards: Array<Card>
mutating func choose(_ card: Card)
{
let chosenIndex = index(of: card)
cards[chosenIndex].isFaceUp = !cards[chosenIndex].isFaceUp
print("debug func choose in memorygame")
}
func index(of card: Card) -> Int
{
for index in 0..<cards.count
{
if cards[index].id == card.id
{
print("debug func index")
return index
}
}
return 0
}
当我取消所有调试注释时,输出为:
-真 -卡片模型中选择调试功能 -索引调试函数 -在记忆游戏中选择调试功能 -真
https://www.youtube.com/watch?v=oWZOFSYS5GE 这是我卡住的视频,直到32:48,所有代码都通过了相同的调试测试。