[英]Why doesn't buttonName.removeFromSuperview always remove the button?
在我的快速游戲中,我們有一個主要的游戲場景,然后一旦您在游戲中死亡,它就會將您帶到一個顯示得分的殘局屏幕上。 然后,用戶可以從該屏幕上點擊按鈕以將場景更改回游戲。 大多數情況下,按鈕會被刪除,並且一切正常,但經常不會將其刪除,而是將其自身覆蓋在游戲場景上。 這是由按鈕運行的代碼-
scoreLabel.removeFromSuperview()
highLabel.removeFromSuperview()
RestartBtn.removeFromSuperview()
self.RestartBtn.removeFromSuperview()
self.highLabel.removeFromSuperview()
self.menuButton.removeFromSuperview()
self.scoreLabel.removeFromSuperview()
self.scene!.view?.presentScene(GameplayScene(), transition: SKTransition.crossFadeWithDuration(0.8))
self.menuButton
和其他所有引用可能都是weak
引用。
也就是說,一旦視圖從超級視圖中刪除,它們就會過時。 它有時可以工作,有時卻不適合在self.menuButton = <something>
引用它,如果在loadView
或viewDidLoad
,那簡直就是危險。
不同的方法
我建議不要過多地使用UI,而是采用更恆定的引用技術,例如hidden
或alpha = 0
。
self.menuButton.removeFromSuperview()
// self.menuButton is stale. You can't re-add your button from that reference
動畫顯示/隱藏視圖
這不會破壞您的引用,並且看起來比removeFromSuperview
好得多:
// Hide with animation
[UIView animateWithDuration:.4f animations:^{
[self.menuButton setAlpha:0]; // Hide with animation
} completion:^(BOOL finished) {
// If you decide to remove the view permanently, do it here
// Without knowing more, I wouldn't recommend it
}];
然后,您可以再次顯示帶有或不帶有動畫的用戶界面:
[self.menuButton setAlpha:1]; // Show without animation
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.