UICollectionView 的selectItem(at:animated:scrollPosition:) 中的animated 确定要选择的项目(如果不在视图中或已在所需位置)是否应以动画方式滚动到。
如果它在视图中,那么这个 animated 属性实际上并没有做任何事情,afaik。
deselectItem(at:animated:) 中的 animated 相同。它什么也不做,就在那里。
我看到影响布局引擎的唯一一件事是如果collectionView 滚动并且您在didSelectItemAt 中有动画,那么它将使这些动画无效。您将不得不延迟单元格中发生的动画(请参阅此答案中的最后一个示例)
正如您已经知道的那样,但对于其他人来说,如果您想为单元格选择事件设置动画,那么您必须在 collectionView(_:didSelectItemAt:) 委托中自己完成。
例子:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
//Briefly fade the cell on selection
UIView.animate(withDuration: 0.5,
animations: {
//Fade-out
cell?.alpha = 0.5
}) { (completed) in
UIView.animate(withDuration: 0.5,
animations: {
//Fade-out
cell?.alpha = 1
})
}
}
如果用户点击一个单元格,上述方法很好,但如果您以编程方式调用selectItem(at:animated:scrollPosition:),它不会触发上述collectionView(_:didSelectItemAt:) 委托,您需要显式调用它来运行您的选择动画。
示例(上一个的附加):
func doSelect(for aCollectionView: UICollectionView,
at indexPath: IndexPath) {
aCollectionView.selectItem(at: indexPath,
animated: true,
scrollPosition: .centeredVertically)
//DispatchQueue after sometime because scroll animation renders
//the animation block in `collectionView(_:didSelectItemAt:)` ineffective
DispatchQueue.main.asyncAfter(deadline: .now() + 0.27) { [weak self] in
self?.collectionView(aCollectionView,
didSelectItemAt: indexPath)
}
}