![](/img/trans.png)
[英]What does `self.view.layoutIfNeeded()` do when changing constraints
[英]Why using self.view.layoutIfNeeded() in Animation cause App Freezing?
在我的應用程序中,一旦用戶進入它,我在儀表板上有太多動畫只發生一次 - 即當用戶第一次進入應用程序時 -
我在viewDidAppear 中以這種方式執行動畫,調用upperViewAnimation()
函數,該函數調用另一個動畫函數,更清楚的是,這是使用的代碼:
func upperViewAnimation() {
contianerTop.constant = 0
UIView.animateWithDuration(0.45, animations: { () -> Void in
self.view.layoutIfNeeded()
}, completion:{(finished) in
if finished {
if noInternetConnection && !noInternetConnectionPopup {
self.noConnectionViewHeight.constant = 50
UIView.animateWithDuration(0.3, animations: {
self.view.layoutIfNeeded()
})
noInternetConnectionPopup = true
openNoInternetConnection()
}
else if noInternetConnection {
self.noConnectionViewHeight.constant = 50
UIView.animateWithDuration(0.3, animations: {
self.view.layoutIfNeeded()
})
}
else {
self.noConnectionViewHeight.constant = 0
UIView.animateWithDuration(0.3, animations: {
self.view.layoutIfNeeded()
}, completion: { (finished) in
self.pullToRefreshAction()
})
}
self.notificationButtonAnimationAndMenuButton()
self.moreAppsLabel.hidden = false
}
})
}
func pullToRefreshAction() {
pullToRefreshContainsFailure = false
addBlurToCellDelegate?.removeBlurFromAllCells()
if firstAppear || userLoggedIn {
self.firstAppear = false
userLoggedIn = false
loadingView2.removeFromSuperview()
sucessView.removeFromSuperview()
var viewHeight:CGFloat = 50
if isiPadFlag {
viewHeight = 60
}
loadingView2 = NSBundle.mainBundle().loadNibNamed("GettingDataView", owner: self, options: nil)[0] as! GettingDataView
loadingView2.frame = CGRect(x: 0, y: 0, width: screenWidth, height: viewHeight)
self.noConnectionView.addSubview(loadingView2)
loadingView2.initView()
gettingDataForFirstTime = true
if showPullToRefreshBool {
self.noConnectionViewHeight.constant = 50
}
UIView.animateWithDuration(0.3, animations: {
self.view.layoutIfNeeded()
})
}
else {
self.noConnectionViewHeight.constant = 0
}
} if !gettingData {
// I called requests to get data
}
}
當我執行前面的代碼時,我的應用程序有時會凍結,而且布局似乎從未改變(即應用程序似乎從未呈現 UI)
我想知道是否使用太多 self.view.layoutIfNeeded() 導致這個問題?
我真的放棄了這個奇怪的問題,
請幫忙,
謝謝。
嘗試在 upperViewAnimation 的第一個完成塊中為 UIView 動畫設置一個完成塊,並繼續在完成塊中而不是在它之外運行你的東西。
如果那沒有幫助。 嘗試在 viewDidLayoutSubviews 中添加您的方法。 還要確保你的動畫一次只被調用一次,viewDidAppear / viewDidLayoutSubviews 可以被多次調用,如果在你的動畫進行中多次調用,事情可能會凍結或變得奇怪。
您可以在動畫運行時通過簡單的 BOOL 標志檢查來解決此問題,並在動畫在完成的塊中完成時將其設置為 false。
我遇到了一個問題,在 UIPropertyAnimator 中調用layoutIfNeeded()
導致凍結,看起來應用程序卡在layoutIfNeeded()
調用處。 在DispatchQueue.main.async
包裝對我的動畫的調用最終解決了我的問題。 我不完全確定發生了什么,但我正在使用對委托方法的調用來觸發動畫,並且可能動畫是在非主線程中開始的,這導致了奇怪的行為。 無論哪種方式,對於在這里谷歌搜索的其他人(如我),嘗試將您的動畫粘貼在 main.async 隊列中。
我有一個無法滿足的約束,即自動布局無法在 ios13 上中斷。 如果你遇到這個問題,祝你找到你的好運,因為我沒有任何指示。 就我而言,這純粹是運氣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.