今天在做东西的时候又遇到这样一个问题,把 UICollectionView
嵌套在 UIViewController
中使用,在想用 scrollToItem()
方法时,怎么都不起作用,找了半天,原来是 位置属性设置错了。
原本的代码是
// viewDidLoad 里面
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "定位", style: .plain, target: self, action: #selector(locatSelectedCell))
// 外部方法
func locatSelectedCell () {
if let lastSelectedIndex = lastSelectionID {
DispatchQueue.main.async {
self.thingsCollectionView.scrollToItem(at: IndexPath(item: lastSelectedIndex, section: 0), at: .centeredHorizontally, animated: true)
}
}
}
错误就出在 at: .centeredHorizontally
,因为我的 collectinoView
的方向是纵向的,所以应该是 at: .centeredVertically
纵向居中显示对应的 cell
func locatSelectedCell () {
if let lastSelectedIndex = lastSelectionID {
DispatchQueue.main.async {
self.thingsCollectionView.scrollToItem(at: IndexPath(item: lastSelectedIndex, section: 0), at: .centeredVertically, animated: true)
}
}
}