如何使用NSTimer使UICollectionView自动滚动?

如何使用NSTimer在水平位置自动滚动UIcollectionView

我正在处理我的项目来源如下:

- (void)viewDidLoad { [super viewDidLoad]; self.endPoint = CGPointMake(0, self.collectionView.frame.size.width); self.scrollingPoint = CGPointMake(0, 0); self.scrollingTimer = [NSTimer scheduledTimerWithTimeInterval:0.015 target:self selector:@selector(onTimer) userInfo:nil repeats:YES]; } - (void)onTimer { self.collectionView.contentOffset = self.scrollingPoint; if (CGPointEqualToPoint(self.scrollingPoint, self.endPoint)) { [self.scrollingTimer invalidate]; } self.scrollingPoint = CGPointMake(self.scrollingPoint.x+1, 0); } 

试着用上面的代码,但不为我工作。

// Swift-3

 var timr=Timer() var w:CGFloat=0.0 override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) configAutoscrollTimer() } override func viewDidDisappear(_ animated: Bool) { super.viewDidAppear(true) deconfigAutoscrollTimer() } func configAutoscrollTimer() { timr=Timer.scheduledTimer(timeInterval: 0.03, target: self, selector: #selector(dashboard_ViewController.autoScrollView), userInfo: nil, repeats: true) } func deconfigAutoscrollTimer() { timr.invalidate() } func onTimer() { autoScrollView() } func autoScrollView() { let initailPoint = CGPoint(x: w,y :0) if __CGPointEqualToPoint(initailPoint, ticker.contentOffset) { if w<collection_view.contentSize.width { w += 0.5 } else { w = -self.view.frame.size.width } let offsetPoint = CGPoint(x: w,y :0) collection_view.contentOffset=offsetPoint } else { w=collection_view.contentOffset.x } } 

//这个效果很好

你应该增加contentOffset.x

 self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x+1, 0); 

如果你想移动到一个特定的单元格,使用

collectionview.delegate。 didSelectItemAtIndexPath(collectionview,indexPath:要显示的单元格的indexPath)

确保你在视图准备好的时候编写这段代码,最好在viewDidAppear()中,以及collectionview的委托不应该是nil。

注意:如果你想在3秒后做这个,说,那么你需要使用

NSTimer.scheduledTimerWithTimeInterval(3,target:self,selector:“showTheCellOfInterest”,userInfo:userInfo,repeatats:true)

并在方法showTheCellOfInterest()中写下这段代码