【学习ios之路:UI系列】实现轮播图效果(UIImageView,UIScrollView,UIPageControl,NSTimer相结合)

 实现效果,在不点击的情况下,自定滚动,点击时,停止.如下图


部分代码如下:

//调用NSTimer方法,自定计时
- (void)autoScroll {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self
                                    selector:@selector(scrollToRight) userInfo:nil repeats:YES];
}
 //实现触发方法
- (void)scrollToRight {
    [UIView animateWithDuration:0.5 animations:^{
      //修改滚动图片的偏移量
     self.shuffleScroll.contentOffset = CGPointMake(self.shuffleScroll.contentOffset.x +
                                                                             kScreenWidth, 0);
    } completion:^(BOOL finished) {
        [self scrollViewDidEndDecelerating:self.shuffleScroll];
        finished = YES;
    }];
}
给图片添加手势,处理手势事件

- (void)handleLongPressAction:(UILongPressGestureRecognizer *)longPress {
     //取消滚动
     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(autoScroll)
                                                                                   object:nil];
    if (longPress.state == UIGestureRecognizerStateBegan) {
        [self.timer invalidate];
        NSLog(@"定时器无效");
    }
    if (longPress.state == UIGestureRecognizerStateEnded) {
        [self performSelector:@selector(autoScroll) withObject:nil afterDelay:0.5];
        NSLog(@"开启定时器");
    }
}
布局图片.并添加手势处理

- (void)setupImageView {
    for (int i = 0; i < self.imageArr.count; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake
                                  (kScreenWidth * i, 0, kScreenWidth, self.frame.size.height)];
        imageView.image = self.imageArr[i];
        imageView.userInteractionEnabled = YES;
        [self.shuffleScroll addSubview:imageView];
        [imageView release];
        
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] 
                                  initWithTarget:self action:@selector(handleLongPressAction:)];
        longPress.minimumPressDuration = 0.01;
        [imageView addGestureRecognizer:longPress];
        [longPress release];
    }
}

该效果,已经整理成为Demo,下载地址如下:

轮播图效果Demo





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值