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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值