提问人:sangyoonlee019 提问时间:7/7/2022 最后编辑:sangyoonlee019 更新时间:7/7/2022 访问量:449
UIView.animate 完成块在主线程中运行吗?
Dose UIView.animate completion block run in main thread?
问:
我制作了一个简单的popupView,并添加了这样的简单动画
// Present
if popup.superView != currentView { currentView.addSubview(popup) }
UIView.animate(withDuration: 0.3, animations: {
popup.alpha = 1
})
// Dismiss
UIView.animate(withDuration: 0.3, animations: {
popup.alpha = 0
}, completion: {
popup.removeFromSuperview()
})
但有时,同时触发的“当前”和“关闭”操作会因“关闭”操作的完成而禁用。所以我加上animationCount
var animationCount: Int = 0
// Present
if popup.superView != currentView { currentView.addSubview(popup) }
animationCount += 1
UIView.animate(withDuration: 0.3, animations: {
popup.alpha = 1
}, completion: {
animationCount -= 1
)
// Dismiss
animationCount += 1
UIView.animate(withDuration: 0.3, animations: {
popup.alpha = 0
}, completion: {
animationCount -= 1
if animationCount == 0 {
popup.removeFromSuperview()
}
})
它看起来不错,似乎运行良好。但我对 UIView.animate 完成块中的数据竞争感到好奇。所以我的问题是“在主线程中运行 UIView.animate 完成块吗?在我看来,如果它在主线程上运行,则不存在数据争用问题,并且不会在superView中出现弹出窗口的情况animationCount
animationCount
如果有人回答我的问题,将不胜感激 谢谢!
答:
1赞
Arik Segal
7/7/2022
#1
答案是肯定的。但为了确保您可以通过添加调试打印来测试它:
UIView.animate(withDuration: 0.3, animations: {
popup.alpha = 0
}, completion: {
print("---- isMainThread: \(Thread.isMainThread) ----")
animationCount -= 1
if animationCount == 0 {
popup.removeFromSuperview()
}
})
评论
0赞
sangyoonlee019
7/7/2022
首先感谢您的回答,如果有任何 UIView.animate 完成块的公共文档线程,您可以分享吗?
评论