我有一个按钮的水平 Collection View 。单击其中一个 View Controller 时,用户将被带到另一个 View Controller 。通常,并非所有按钮都是可见的,因此我希望所选按钮位于 Collection View 的最左侧。
我试图使用scrollToItem函数来做到这一点。问题是,它每次都会将 Collection View 一直滚动到右侧。
相关代码:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return labelArray.count
}
//frees up the collection view when the scroll is active
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isScrolling = true
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
//possible problem
if isScrolling == false {
collectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.left, animated: false)
}
let myLabel = cell.viewWithTag(1) as! UILabel
let myArray = labelArray[indexPath.row]
myLabel.text = labelArray[indexPath.row]
myLabel.textColor = UIColor.white
if myArray == labelArray[1] {
cell.backgroundColor = UIColor.black
} else {
cell.backgroundColor = UIColor(red: 56/255, green: 120/255, blue: 195/255, alpha: 1)
}
return cell
}
任何帮助将不胜感激。
最佳答案
您正在 cellForItemAt 方法中调用scrollToItem 方法,该方法会为 Collection View 中的每个可见单元格调用。因此,您实际上是在尝试滚动到每个单元格变得可见。尝试在 didSelectItemAt 方法中调用scrollToItem 方法,如下所示:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
}
仅当选择单元格时才会调用 didSelectItemAt 并提供所选单元格的 IndexPath。
关于ios - ScrollToItem 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46569781/