定时器 · UIScrollView滚动视图自动翻页滚动

2 篇文章 0 订阅
2 篇文章 0 订阅
@property (nonatomic, strong) UIScrollView *ydyScrollView;
@property (nonatomic ,strong) NSArray *imgArr;  // 图片数组
@property (nonatomic ,strong) UIPageControl *page;  // 分页控件
@property (nonatomic ,strong) NSTimer *timer;   // 定时器

在 viewDidLoad 中

// 创建引导页滚动视图
self.ydyScrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
self.ydyScrollView.delegate = self;
self.ydyScrollView.backgroundColor = [UIColor redColor];
[self.view addSubview:self.ydyScrollView];

// 创建图片数组
_imgArr = @[@"11.jpg",@"12.jpg",@"13.jpg"];

// for 循环加入图片
for (int i = 0; i < _imgArr.count; i ++) {

    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * i, 0, self.view.frame.size.width, self.view.frame.size.height)];
    imgView.image = [UIImage imageNamed:_imgArr[i]];
    [self.ydyScrollView addSubview:imgView];
    imgView.userInteractionEnabled = YES;
}

// 设置滚动范围
_ydyScrollView.contentSize = CGSizeMake(self.view.frame.size.width * _imgArr.count, 0);
// 设置翻页滚动
_ydyScrollView.pagingEnabled = YES;
// 取消弹簧效果
_ydyScrollView.bounces = NO;

// 设置分页控件
_page = [[UIPageControl alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 100) / 2, self.view.frame.size.height - 150, 100, 100)];
_page.numberOfPages = _imgArr.count;
_page.pageIndicatorTintColor = [UIColor blackColor];
_page.currentPageIndicatorTintColor = [UIColor redColor];
[self.view addSubview:_page];

//自定义一个定时器方法
[self yyTimer];

//定时器方法

- (void)yyTimer{

    //设置定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(change:) userInfo:nil repeats:YES];
}
//关闭定时器
- (void)removeTimer{

    if (_timer) {

        if ([self.timer isValid]) {

            [self.timer invalidate];
            _timer = nil;
        }
    }
}
//定时器执行方法
- (void)change:(NSTimer *)time{
    [self.ydyScrollView setContentOffset:CGPointMake((self.page.currentPage + 1) * self.view.frame.size.width, 0) animated:NO];
}
// 滚动视图的代理方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 分页控件跟随滚动视图的滚动页变换
    _page.currentPage = _ydyScrollView.contentOffset.x / self.view.frame.size.width;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值