大佬教程收集整理的这篇文章主要介绍了UICollectionView 实现,自动滚动、一屏横向显示3个view,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
实现UICollectionView的自动滚动,以及一屏下,中间显示一个view,两边显示半个view的效果,
如图:
自动滚动是使用Timer实现,每个一段时间让UICollectionView自动滚动下即可。
//自动滚动计时器 var autoScrollTimer:Timer?
var index: Int = 0
func startTimer() { //设置一个定时器,每三秒钟滚动一次 autoScrollTimer = Timer.scheduledTimer(timeInterval: 3,target: self,SELEctor: #SELEctor(UICollectionViewTypeOneController.scroll),userInfo: nil,repeats: truE) }
//计时器时间一到,滚动一张图片 @objc func scroll(){ index = index + 1 index = index >= dataCollection.count ? 0 : index collectionView.scrollToItem(at: IndexPath.init(row: index,section: 0),at: .centeredHorizontally,animated: truE) }
class ProductAHorCollectionViewFlowLayout: UICollectionViewFlowLayout { override func prepare() { super.prepare() } override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint,withScrollingVeLocity veLocity: CGPoint) -> CGPoint { } }
prepare方法我们做一些初始化操作,如设置Item的大小和左右边距等
let left = (self.collectionView!.bounds.width - itemWidth) / 2 let top = (self.collectionView!.bounds.height - itemHeight) / 2 self.sectionInset = UIEdgeInsetsmake(top,left,top,left)
至此我们已经实现了一个view居中显示,两边显示个头的效果,但@R_675_10950@们要保证,用户滑动结束后,中间的view一直显示在中间,所以要实现下targetContentOffset方法。
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint,withScrollingVeLocity veLocity: CGPoint) -> CGPoint { //停止滚动时的可见区域 let lastRect = CGRect(x: proposedContentOffset.x,y: proposedContentOffset.y,width: self.collectionView!.bounds.width,height: self.collectionView!.bounds.height) //当前屏幕中点,相对于collect view上的x坐标 let centerX = proposedContentOffset.x + self.collectionView!.bounds.width * 0.5; //这个可见区域内所有的单元格属性 let array = self.layoutAttributesForElements(in: lastRect) //需要移动的距离 var adjustOffsetX = CGFloat(MAXFLOAT); for attri in array! { //每个单元格里中点的偏移量 let deviation = attri.center.x - centerX //保存偏移最小的那个 if abs(deviation) < abs(adjustOffsetX) { adjustOffsetX = deviation } } //通过偏移量返回最终停留的位置 return CGPoint(x: proposedContentOffset.x + adjustOffsetX,y: proposedContentOffset.y) }
以上是大佬教程为你收集整理的UICollectionView 实现,自动滚动、一屏横向显示3个view全部内容,希望文章能够帮你解决UICollectionView 实现,自动滚动、一屏横向显示3个view所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。