IOS开发控件视图day15:UIPageControl设置定时器自动翻页,以及更改小圆点背景图片

.h文件

@property(nonatomic,strong)UIScrollView *scrollView0;
@property (strong, nonatomic) UIPageControl *pageControl0;
@property (nonatomic,strong) NSTimer *nstime;

.m文件(具体循环view内容已省略)

_scrollView0.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width*5, 0);
_scrollView0.showsVerticalScrollIndicator = NO;//隐藏滚动条
_scrollView0.pagingEnabled = YES;//开启分页功能
_scrollView0.delegate = self;

_pageControl0 = [[UIPageControl alloc]init];
_pageControl0.backgroundColor = [UIColor whiteColor];
_pageControl0.numberOfPages = 5;
_pageControl0.currentPage = 0;//默认起始页
//当前页背景样式图片
[_pageControl0 setValue:[UIImage imageNamed:@"菜单-滑动切换"] forKeyPath:@"_currentPageImage"];
//非当前页背景样式图片
 [_pageControl0 setValue:[UIImage imageNamed:@"菜单-滑动切换灰"] forKeyPath:@"_pageImage"];

//设置定时器方法
self.nstime=[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(scrolllab) userInfo:nil repeats:YES];

-(void)scrollImg
{
    //NSLog(@"1");
    //获取当前页码
    NSInteger page=_pageControl0.currentPage;
    //判断最后一页,回到第一页否则页码加1
    if (page==_pageControl0.numberOfPages-1) {
        page=0;
    }else
    {
        page++;
    }
    //页宽*(页码+1)
    CGFloat offsetX=page*_scrollView11.frame.size.width;
    //赋值
    [_scrollView0 setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //获取x方向偏移值
    CGFloat offsetX = scrollView.contentOffset.x;
    //让图片翻页过半时页码显示下一个
    offsetX=offsetX+(scrollView.frame.size.width*0.5);
    //偏移值除以图片或每页宽度得到第几页
    int page= offsetX / scrollView.frame.size.width;

    _pageControl0.currentPage=page;
}

//拖拽时
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    //停止计时器,不可重用
    [self.nstime invalidate];
    self.nstime=nil;
}
//停止拖拽时
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    //重启一个计时器
    self.nstime=[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(scrollImg) userInfo:nil repeats:YES];
}

你可能感兴趣的:(IOS控件基础,ios)