我正在尝试处理设备轮换,并且(在轮换过程中)做出一些努力"将我的collectionView滚动到指定的项目。 所以如果我在DispatchQueue.main.async()中这样做,一切都会更新。
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator)
{
DispatchQueue.main.async {
let indexPath = IndexPath(item: self.pageControl.currentPage, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}
}
但我只是在willTransition func中执行它而不涉及DispatchQueue.main.async()接口doest不更新,没有任何反应。
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator)
{
let indexPath = IndexPath(item: self.pageControl.currentPage, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}
为什么呢?它是什么(willTrasition func背景下的DispatchQueue)魅力?
答案 0 :(得分:1)
尝试使用协调器,以便将集合视图作为旋转的一部分滚动。
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator)
{
coordinator.animate(alongsideTransition: { (context) in
let indexPath = IndexPath(item: self.pageControl.currentPage, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}, completion: nil)
}
不使用DispatchQueue.main.async
时代码失败的最可能原因是您最终尝试滚动太快,当您使用它时,滚动会延迟很长时间才能生效。