iOS 轮播视图的实现方式 和 RunLoopMode 的注意

通过 CollectionView 实现

需要哪些组件

  • collectionView
  • pageControl
  • NSTimer

collectionView

  • cell 图片的载体
  • contentsOffset 内容的偏移量
  • indexpath 当前滚动的cell的indexPath

如何轮播?

  NSInteger curIndex = (self.collectionView.contentOffset.x + self.layout.itemSize.width * 0.5) / self.layout.itemSize.width;
  //计算将要滚到的Index,如果是将要滚到第一个,就把toIndex = 0;
  NSInteger toIndex = curIndex + 1;
  if (toIndex == self.totalPageCount) {
    toIndex = 0;
  [self.collectionView scrollToItemAtIndexPath:indexPath
                        atScrollPosition:UICollectionViewScrollPositionNone
                              animated:YES];

pageControl

//需要在scrollViewDidScroll中计算 currentPage
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {

    int itemIndex = (scrollView.contentOffset.x +
                   self.collectionView.xjy_width * 0.5) / self.collectionView.xjy_width;
    itemIndex = itemIndex % self.imageUrls.count;
    _pageControl.currentPage = itemIndex;
}

NSTimer

  • RunLoopMode kCFRunLoopCommonModes(RunLoop的问题看我的Runloop博文)
  • @selector() 要执行自动轮播的方法

  if (self.timer) {
    CFRunLoopTimerInvalidate(self.timer);
    CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), self.timer, kCFRunLoopCommonModes);
  }

  __weak __typeof(self) weakSelf = self;
  CFRunLoopTimerRef timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + _timeInterval, _timeInterval, 0, 0, ^(CFRunLoopTimerRef timer) {
    [weakSelf autoScroll];
  });

  self.timer = timer;
  CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes);

你可能感兴趣的:(iOS)