UIPageControl以及滚动视图定时滚动的相关代码如下:
#import "TRRootViewController.h"
#import "TRSubViewController.h"
#define SCROLL_W 320
#define SCROLL_H 568
@interface TRRootViewController ()<UIScrollViewDelegate>
@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,strong)UIPageControl *pageControl;
@end
@implementation TRRootViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
#pragma mark - 页面控制
-(void)updataPage
{
self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(110, 450, 80, 50)];
[self.view addSubview:self.pageControl];
//设置有多少页码 4
self.pageControl.numberOfPages = 4;
//设置当前页码
self.pageControl.currentPage = 0;
//循环的滚动
[NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(changedImage) userInfo:nil repeats:YES];
}
#pragma mark - 隔一段时间更新图片
-(void)changedImage
{
//声明一个CGPoint结构体
CGPoint point = self.scrollView.contentOffset;
//设置布尔类型的值
static BOOL isEnd = YES;
//判断
if(isEnd)
{
point.x++;
}
else
{
point.x--;
}
//让滚动视图动起来
self.scrollView.contentOffset = point;
//更新页面控制器上的页码
self.pageControl.currentPage = (int)(point.x/SCROLL_W);
//循环滚动 滚回来
if(SCROLL_W *3 < point.x)
{
//到头了 右侧 NO
isEnd = NO;
point.x--;
}
else if(0 == point.x)
{
//从头滚动 左侧 YES
isEnd = YES;
}
}
#pragma mark - 创建滚动视图
-(void)createUIScrollView
{
//实例化滚动视图
self.scrollView = [[UIScrollView alloc] init];
//位置和大小
self.scrollView.frame = CGRectMake(0, 0,
320, 568);
//设置滚动视图的滚动范围
self.scrollView.contentSize =CGSizeMake(SCROLL_W*4, SCROLL_H);
//设置是否开启分页显示
self.scrollView.pagingEnabled = YES;
//设置拖拽的弹簧效果
self.scrollView.bounces =YES;
//设置委托
self.scrollView.delegate = self;
//添加到父视图上
[self.view addSubview:self.scrollView];
//载入图片
for(int i = 0 ; i < 4 ; i++)
{
//UIImageView显示图片
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"w%d.jpg",i+1]]];
//设置每一个imgView的frame
imgView.frame = CGRectMake(SCROLL_W*i , 0, SCROLL_W, SCROLL_H);
//把imgView添加到scrollView上
[self.scrollView addSubview:imgView];
}
}
#pragma mark - 载入视图
- (void)viewDidLoad
{
[super viewDidLoad];
[self createUIScrollView];
[self updataPage];
}
#pragma mark - 拿到当前滚动视图页码
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
NSLog(@"%f",scrollView.contentOffset.x);
//只要大于960即可跳转
}
#pragma mark - 使用委托方法更新页码
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
self.pageControl.currentPage = scrollView.contentOffset.x/SCROLL_W;
}
#pragma mark - 低内存警告
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end