iOS 图片循环播放效果

2016-04-11  本文已影响566人  虫子疯狂也可怕

在类中什么两个属性

@property (nonatomic,assign) BOOL isDragging;               //是否正在拖动
@property (nonatomic,strong)NSTimer *timer;                 //设置动画

用作判断是否在拖地和添加动画

先创建scrollview

UIView  *view4Header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, 100)];

UIScrollView * _scrollview=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kWIDTH, 100)];
    _scrollview.contentSize=CGSizeMake(kWIDTH*6, 100);
//    _scrollview.contentOffset = CGPointMake(0, 0);
    _scrollview.pagingEnabled=YES;
    _scrollview.delegate=self;
    _scrollview.showsHorizontalScrollIndicator = NO;
    [view4Header addSubview:_scrollview];

    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake((kWIDTH - 80)/2, view4Header.frame.size.height - 20, 80, 10)];
    _pageControl.numberOfPages = 4;
    _pageControl.currentPage = 0;
    [view4Header addSubview:_pageControl];
    
    //贴图
    for (int i=0; i<6; i++) {

        int y=i + 5;
        if (i == 5) {
            y = 6;
        }else if (i == 0){
            y = 9;
        }

        UIImageView*imageView=[[UIImageView alloc]initWithFrame:CGRectMake(i*kWIDTH, 0, kWIDTH, 100)];
        imageView.image=[UIImage imageNamed:[NSString stringWithFormat:@"pic_n000%d",y]];
        [_scrollview addSubview:imageView];
    }

//  设置时钟动画 定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.5f target:self selector:@selector(update:) userInfo:nil repeats:YES];
    //  将定时器添加到主线程
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

实现定时移动效果

- (void)update:(NSTimer *)timer{
    //定时移动
    
    CGPoint offSet = _scrollview.contentOffset;
    
    if (_isDragging == YES) {
        return ;
    }
    
    offSet.x = offSet.x + kWIDTH;
   
    [_scrollview setContentOffset:offSet animated:YES];
    
    if (offSet.x / kWIDTH == 5) {
        [_scrollview setContentOffset:CGPointMake(0, 0)];
    }
}

最后添加上ScrollView的代理方法,使其可以滑动拖动

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    _isDragging = YES;
}
//  停止滚动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    float offset = _scrollview.contentOffset.x;
    
    if (offset > kWIDTH*4) {
        [_scrollview setContentOffset:CGPointMake(kWIDTH, 0)];
    }

    if (offset < kWIDTH) {
        [_scrollview setContentOffset:CGPointMake(4*kWIDTH, 0)];
    }
    _isDragging = NO;
}
上一篇下一篇

猜你喜欢

热点阅读