为什么使用 func 时 UI 没有及时更新@IBAction?



这是@ibaction func

的代码
@IBAction func touchCard(_ sender: UIButton) {
    flipCount += 1
    if let index = buttonCollection.firstIndex(of: sender) {
        game.chooseCard(at: index)
        updateViewFromModel() // I set breakpoint at here
    }
}

浓度。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
        }
    }
}
}

Func UpdateViewFromemel()

的代码

卡片文件,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项目集中游戏的一部分。
当我逐步跟踪代码时,我发现了一些令人困惑的东西。

  1. 如前所述,我设置了一个断点@ibaction func touchCard中的UpdateViewFromemel()(_发送者:uibutton)
  2. 然后我单击Xcode的"运行"按钮
  3. iPhone模拟器出来了。
  4. 默认的UI映像无需单击
  5. 我在第一行中从左到右单击了第一个"卡"(实际上是按钮)
  6. Xcode反应,UI保持与默认值相同
  7. 我开始使用LLDB调试代码,然后进入Func UpdateViewFromemel()
  8. 当我逐步到第64行时,它表明第一张卡的iSfaceup是正确的,因为我刚刚单击此卡。
  9. 让我们继续前进,我登上了第68行。必须执行65行和66行!我认为,执行第65行和66时UI应该更改。但是,UI为什么不及时更新?
  10. 我在Func UpdateViewFromeDel中执行了左代码,因为我没有单击任何其他卡。
  11. 最后,它到达@ibaction func触摸卡的结尾,UI仍然与默认值相同。
  12. 我单击了"继续程序执行"按钮,UI响应正确。我感到很奇怪。

我想知道的是,在第9步中,为什么不及时更新UI。

我将非常感谢您的帮助!

在视图上进行更改时,它会等待重新循环,因此不会立即更新视图。IBACTION没有错,您将更改放在其他地方并设置一个断点,这不会有任何区别。

这可能是由于慢速模拟器所致,因为我也面临慢模拟器问题,我不知道其他人是否也面临着这个问题,我怀疑您面对这个问题,但我不是当然。

1-使用Xcode 9.2和ios11的模拟器时,您的代码没有错。

2-尝试一下您的设备

最新更新