当滚动视图快速滚动时,如何滚动collectionView?

时间:2018-06-25 13:07:40

标签: ios swift uiscrollview uicollectionview

我有Scrollview和Collectionview,它们都可以水平滚动

scrollview有页面,并且我希望在scrollview滚动时也滚动collectionview并选择相同的索引collectionview单元格作为scrollview页面索引

这里的问题是,滚动视图滚动后,还会滚动collectionview,并且它选择与scrollview页面索引相同的单元格,但之后collectionview不会自动滚动。

很抱歉,问题的格式可能不好,我是新来的人

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell=collectionView.dequeueReusableCell(withReuseIdentifier: "mycell", for: indexPath) as! MenuListCollectionViewCell
    cell.commoninit(name: ListOfMenu[indexPath.row])

   let IndexForCol = (scrollview.contentOffset.x / scrollview.frame.size.width).rounded()

    if selectedIndex == Int(indexPath.row)
    {

        cell.backgroundColor = UIColor(hue: 0.6167, saturation: 1, brightness: 0.97, alpha: 1.0)
        cell.layer.cornerRadius = 14

    }
    if indexPath.row == Int(IndexForCol) {
        cell.backgroundColor = UIColor(hue: 0.6167, saturation: 1, brightness: 0.97, alpha: 1.0)

    }
    else
    {
        cell.backgroundColor = UIColor.clear
    }

    return cell
}



func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {   
 selectedIndex = indexPath.row
    UIView.animate(withDuration: 0.5, animations: {
        self.scrollview.contentOffset.x = self.scrollview.frame.width*CGFloat(indexPath.row)
    })

}




func scrollViewDidScroll(_ scrollView: UIScrollView) {
  let indexOfPage = round(scrollview.contentOffset.x / scrollview.frame.size.width)
  UIView.animate(withDuration: 0.5, animations: {
       self.collectionview.scrollToItem(at:IndexPath(item: Int(indexOfPage), section: 0), at: .right, animated: false)
  })
 collectionview.reloadData()

}

模拟器图片:

enter image description here

1 个答案:

答案 0 :(得分:2)

scrollViewDidScroll会同时被collectionView和scrollView调用,因此请给scrollView一个标签

//

func scrollViewDidScroll(_ scrollView: UIScrollView) {

  if scrollView.tag == 2 { // scrollView scrolled 
      use collectionView's scrollToItem
  }
  else {                    // collectionView scrolled 
       set contentOffset to the scrollView
  }

}