【问题标题】:How to make UICollectionView auto scroll using NSTimer?如何使用 NSTimer 使 UICollectionView 自动滚动?
【发布时间】:2016-05-29 04:10:47
【问题描述】:

如何使用 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);
}

用上面的代码试过了,但对我不起作用。

【问题讨论】:

  • 你不应该为此使用 NSTimer。 CADisplayLink 链接到显示器,因此将为您提供更新屏幕相关事件的更好方法。这在 WWD 2015 或 WWDC 2014 的 scrollView 会话中得到了很好的解释。
  • 先尝试设置数据源,然后在您的 viewdidload 中重新加载或尝试在 viewwillappear 中显示。然后调用你的计时器

标签: ios objective-c swift cocoa-touch


【解决方案1】:

斯威夫特 4.2

带有 Runloop 和 Timer 块。调整 0.015 和 0.25 值以匹配您所需的速度。

    var carousalTimer: Timer?
    var newOffsetX: CGFloat = 0.0
    func startTimer() {

        carousalTimer = Timer(fire: Date(), interval: 0.015, repeats: true) { (timer) in

            let initailPoint = CGPoint(x: self.newOffsetX,y :0)

            if __CGPointEqualToPoint(initailPoint, self.collectionView.contentOffset) {

                if self.newOffsetX < self.collectionView.contentSize.width {
                    self.newOffsetX += 0.25
                }
                if self.newOffsetX > self.collectionView.contentSize.width - self.collectionView.frame.size.width {
                    self.newOffsetX = 0
                }

                self.collectionView.contentOffset = CGPoint(x: self.newOffsetX,y :0)

            } else {
                self.newOffsetX = self.collectionView.contentOffset.x
            }
        }

        RunLoop.current.add(carousalTimer!, forMode: .common)
    }

【讨论】:

    【解决方案2】:

    // 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
            }
        }
    

    // 这很好用

    【讨论】:

    • 我想一张一张地滚动图片,我试过你的代码它自动滚动整个收藏集。我想要一个一个自动滚动。请更新我
    • 你能检查一下这个stackoverflow.com/q/39158680/2522603。我只是从你的答案中复制过来的。
    • ticker.contentOffset 是什么?
    • ticker.contentOffset 可以是self.collectionView.contentOffset
    • 是的,这是collectionview。
    【解决方案3】:
     @IBOutlet weak var collection_scroll: UICollectionView! // Outlet
     var Scrollinftimer = Timer() // Set Timer 
     let Image_Scroll : [String] = ["ic_girl1","ic_girl2"] // Set Your Images
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return Image_Scroll.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomcollectionCellCollectionViewCell", for: indexPath) as! CustomcollectionCellCollectionViewCell
    
        cell.img_scrollcoll.image = UIImage(named : Image_Scroll[indexPath.row])
    
        var rowIndex = indexPath.row
        let Numberofrecords : Int = Image_Scroll.count - 1
        if (rowIndex < Numberofrecords)
        {
            rowIndex = (rowIndex + 0) // 1
        }
        else
        {
            rowIndex = 0
        }
    
        Scrollinftimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(ViewController.startTimer(timersset:)), userInfo: rowIndex, repeats: true)
    
    
        return cell
    }
    
    @objc func startTimer(timersset : Timer)
    {
        UIView.animate(withDuration: 1.0, delay: 0, options: .curveEaseOut, animations:
        {
            self.collection_scroll.scrollToItem(at: IndexPath(row: timersset.userInfo! as! Int,section:0), at: .centeredHorizontally, animated: false)
        }, completion: nil)
    }
    

    【讨论】:

      【解决方案4】:
       var carousalTimer: Timer?
          var newOffsetX: CGFloat = 0.0
          func startTimer() {
      
              carousalTimer = Timer(fire: Date(), interval: 0.015, repeats: true) { (timer) in
      
                  let initailPoint = CGPoint(x: self.newOffsetX,y :0)
      
                  if __CGPointEqualToPoint(initailPoint, self.image_slider_out.contentOffset) {
      
                      if self.newOffsetX < self.image_slider_out.contentSize.width {
                          self.newOffsetX += 2
                      }
                      if self.newOffsetX > self.image_slider_out.contentSize.width - self.image_slider_out.frame.size.width {
                          self.newOffsetX = 0
                      }
      
                      self.image_slider_out.contentOffset = CGPoint(x: self.newOffsetX,y :0)
      
                  } else {
                      self.newOffsetX = self.image_slider_out.contentOffset.x
                  }
              }
      
              RunLoop.current.add(carousalTimer!, forMode: .common)
          }
      

      【讨论】:

      • 注意:image_slider_out 是我的收藏视图名称
      • 在 viewDidLoad() 调用 startTimer() 函数后
      【解决方案5】:

      你应该增加contentOffset.x:

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

      【讨论】:

        【解决方案6】:

        如果您想移动到特定单元格,请使用

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

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

        注意:如果你想在 3 秒后执行此操作,比如说,那么你需要使用

        NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "showTheCellOfInterest", userInfo: userInfo, repeats: true)

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

        【讨论】:

          【解决方案7】:

          https://github.com/mohankrishnameruva/AutoScrollCollectionView

          您可以使用此 pod AutoScrollCollectionView,只需从情节提要中的 AutoScrollCollectionView 子类化您的集合视图,然后使用所需的 TimeInterval collectionView 在集合视图上调用此方法。 startAutoScrolling(withTimeInterval: TimeInterval(确切地说: 2.0)!)

          【讨论】:

            【解决方案8】:

            试试这个代码

            -(void) autoScrollImageSlider {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    if(bannerArr.count == 0) {
                        return;
                    }
                    if (counter < bannerArr.count) {
                        _pagerView.currentPage = counter;
                        NSIndexPath *nextIndexPath = [NSIndexPath indexPathForRow:counter inSection:0];
                        [self.collectionView scrollToItemAtIndexPath: nextIndexPath atScrollPosition: UICollectionViewScrollPositionCenteredHorizontally animated:YES];
                        counter += 1;
                       
                    }else {
                        counter = 0;
                        _pagerView.currentPage = counter;
                        NSIndexPath *nextIndexPath = [NSIndexPath indexPathForRow:counter inSection:0];
                        
                        [self.collectionView scrollToItemAtIndexPath: nextIndexPath atScrollPosition: UICollectionViewScrollPositionCenteredHorizontally animated:YES];
                        counter = 1;
                        
                    }
                });
                
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2021-01-15
              • 2014-11-19
              • 1970-01-01
              • 2020-09-20
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多