我有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()
}
模拟器图片:
答案 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
}
}