这是@IBAction函数的代码
@IBAction func touchCard(_ sender: UIButton) {
flipCount += 1
if let index = buttonCollection.firstIndex(of: sender) {
game.chooseCard(at: index)
updateViewFromModel() // I set breakpoint at here
}
}
Concentration.swift文件,MVC模型的一部分
class Concentration {
var cards = [Card]()
var numberOfPairsOfCards: Int
var identifierOfOneAndOnlyOneCard: Int? {
didSet {
print("identifierOfOneAndOnlyOneCard: \(identifierOfOneAndOnlyOneCard)")
}
}
init(numberOfPairsOfCards: Int) {
self.numberOfPairsOfCards = numberOfPairsOfCards
for _ in 0..<numberOfPairsOfCards {
let card = Card()
cards += [card, card]
}
}
func chooseCard(at Index: Int) {
print("Index: \(Index)")
if !cards[Index].isMatched {
if let matchIndex = identifierOfOneAndOnlyOneCard, matchIndex != Index {
// check if cards match
if cards[matchIndex].identifier == cards[Index].identifier {
cards[matchIndex].isMatched = true
cards[Index].isMatched = true
}
cards[Index].isFaceUp = true
identifierOfOneAndOnlyOneCard = nil
} else {
// either no cards or 2 cards are face up
for flipDownIndex in cards.indices {
cards[flipDownIndex].isFaceUp = false
}
cards[Index].isFaceUp = true
identifierOfOneAndOnlyOneCard = Index
}
}
}
}
the code of func updateViewFromModel()
Card.swift文件,MVC模型的一部分
struct Card {
var isFaceUp: Bool = false
var isMatched: Bool = false
var identifier = getUniqueIdentifier()
static var uniqueIdentifier: Int = 0
static func getUniqueIdentifier() -> Int{
uniqueIdentifier += 1
return uniqueIdentifier
}
}
这些代码是来自 CS193p 的项目集中游戏的一部分。
当我一步步跟踪代码时,我发现了一些令人费解的地方。
- 如前所述,我在 @IBAction 中的 updateViewFromModel() func touchCard(_ sender: 界面按钮)
- 然后我点击 Xcode 的“运行”按钮
- iPhone模拟器出来了。
- the default UI image without any clicking
- 我点击了第一行从左到右的第一张“卡片”(实际上是一个按钮)
- Xcode reacted用户界面与默认界面保持一致
- 我开始使用 LLDB 调试代码,然后进入 func updateViewFromModel()
- When I stepped over to Line 64 , 它显示第一张卡片的 isFaceUp 是真的,因为我刚刚点击了这张卡片。
- 让我们继续,I stepped over to Line 68 .必须执行第65和66行!我的想法是,在执行第 65 和 66 行时, UI应该会变,但是,为什么UI没有及时更新?
- 我完成了 func updateViewFromModel 中左侧代码的执行,因为我没有点击任何其他卡片。
- Finally it came to the end of @IBAction func touchCard , UI 仍然与默认相同。
- 我点击了“继续执行程序”按钮,the UI responded correctly .我觉得很奇怪。
我想弄明白的是第9步为什么没有及时更新UI。
非常感谢您的帮助!
最佳答案
当您对 View 进行更改时,它会等待重绘周期,因此 View 不会立即更新。 IBAction 没有任何问题,您将更改放在其他地方并设置一个断点,它不会有任何区别。
关于ios - 为什么使用@IBAction func 时UI 没有及时更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55034997/