scrollToItem出错
原本我是这样写的
// 滚动到指定位置 DispatchQueue.main.async { [weak self] in let indexPath = IndexPath(row: self!.currentNumber - 1, section: 0) self!.collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
}
发现问题,UICollectionView在iOS14上滚动不到指定indexPath,而在iOS14以下是正常的,莫名其妙
解决方法,添加UICollectionView公开扩展方法,计算滚动偏移量
public extension UICollectionView { func scrollTo(indexPath: IndexPath, animated: Bool = true) { let attributes = collectionViewLayout.layoutAttributesForItem(at: indexPath)! setContentOffset(attributes.frame.origin, animated: animated) } }
修改后的代码
// 初始滚动到指定位置
DispatchQueue.main.async { [weak self] in let indexPath = IndexPath(row: self!.currentNumber - 1, section: 0) self!.collectionView.scrollTo(indexPath: indexPath) }