3D轮播图

来源:互联网 发布:汉仪中黑简体下载 mac 编辑:程序博客网 时间:2024/06/18 13:34
  • 前言:在实际开发中,轮播图是很多app必备的展示功能。有的时候我们想让轮播图展示的效果不一样,比如像Mac版网易云音乐的轮播图,就是3D版的轮播图。我使用iCarousel这个能实现”旋转木马”的三方库封装了一个简单的3D轮播图。iCarousel这个库我会抽一片文章来介绍。

  • 先上效果图:

    这里写图片描述

  • 核心代码:

    • 当我们用手拖动图片再放开的时候,定时器的由暂停到重写开启的时间的处理问题。我用给NSDate添加一个分类的形式实现:当再次松手的时候,定时器在2秒后开始运行(2秒是设定的轮播时间);
    + (NSDate *)intervalSecondsTime{NSDate *date = [NSDate date];//延迟2秒NSDate *lastDay = [self dateWithTimeInterval:2 sinceDate:date];return lastDay;}
    • API:

      @interface FF3DBanner : UIView/*************外界API**********//** 传入item的url */@property(strong,nonatomic)NSArray <NSString *> *displayArray;/**当前选中指示器的颜色*/@property(strong,nonatomic)UIColor *currentColor;/** 非选中状态下指示器德颜色 */@property(strong,nonatomic)UIColor *normalColor;/** 每个item的尺寸 */@property (nonatomic, assign) CGSize itemSize;/** 点击事件 会返回点击的index  和 数据数组 */@property (nonatomic, copy) void (^clickItemAction)(NSInteger, NSArray *)@end
    • 具体的实现代码:

    #pragma mark -- 数据源- (NSInteger)numberOfItemsInCarousel:(iCarousel *)carousel{return _displayArray.count;}- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view{if (view == nil){    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.itemSize.width, self.itemSize.height)];    imageView.contentMode = UIViewContentModeScaleAspectFit;    NSString *itemUrl = _displayArray[index];    if ([itemUrl hasPrefix:@"http"]) {      [imageView sd_setImageWithURL:[NSURL URLWithString:itemUrl] placeholderImage:nil options:SDWebImageRetryFailed];    }else{        imageView.image = [UIImage imageNamed:itemUrl];    }    view = imageView;}return view;}
  //代理方法- (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index{    if (self.clickItemAction) {        self.clickItemAction(index,self.displayArray);    }}-(void)addTimer{    if (!self.timer) {        self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];        //添加到runloop中        [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];    }}//暂停定时器- (void)stopTimer{    [self.timer setFireDate:[NSDate distantFuture]];}- (void)dealloc{    [self.timer invalidate];    self.timer = nil;}- (void)nextImage{    NSInteger index = self.carousel.currentItemIndex + 1;    if (index == _displayArray.count ) {        index = 0;    }    [self.carousel scrollToItemAtIndex:index                              animated:YES];}- (void)carouselDidScroll:(iCarousel *)carousel;{    self.pageControl.currentPage = carousel.currentItemIndex;}- (void)carouselWillBeginDragging:(iCarousel *)carousel{    [self stopTimer];}- (void)carouselDidEndDecelerating:(iCarousel *)carousel{    //重新再2秒过后开启定时器     [self.timer setFireDate:[NSDate intervalSecondsTime]];}- (void)carouselDidEndDragging:(iCarousel *)carousel willDecelerate:(BOOL)decelerate{    //开启定时器    [self addTimer];}
  • 结尾:您可以在这里下载到本文的demo