[英]How can I scroll collectionView when scrollview scrolls in swift?
I have Scrollview and Collectionview, both of them scrolls horizontally 我有Scrollview和Collectionview,它们都可以水平滚动
scrollview have pages and I want when scrollview scrolls, also scroll collectionview and select same indexed collectionview cell as scrollview page index scrollview有页面,并且当scrollview滚动时,我也想
the problem here is that after scrollview scrolls, also scrolls collectionview and it selects cell same indexed as scrollview pages, but after that collectionview doesn't scrolls itself. 这里的问题是,在scrollview滚动之后,还会滚动collectionview,并且它选择与scrollview页面索引相同的单元格,但是在此之后collectionview不会自动滚动。
Sorry maybe bad format of question, I am new here 抱歉,问题格式不好,我是新来的
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()
}
Simulator image: 模拟器图片:
scrollViewDidScroll
is called for both the collectionView and the scrollView so give a tag to the scrollView then 对collectionView和scrollViewDidScroll
都调用了scrollViewDidScroll,因此给滚动视图添加一个标签,然后
// //
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.tag == 2 { // scrollView scrolled
use collectionView's scrollToItem
}
else { // collectionView scrolled
set contentOffset to the scrollView
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.