滚动视图

#import "ViewController.h"

@interface ViewController ()

{

UIScrollView *scroll;  //滚动视图

NSArray *arr;  //数组

UIPageControl *p;  //分页控件

NSInteger pagecount; //记录页数

NSTimer *timer; //计时器

}

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

//获取屏幕的宽

float width = self.view.frame.size.width;

//获取屏幕的高

float height = self.view.frame.size.height;

//创建滚动视图

scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, width, height)];

float x = 0.0;

for (int i = 0 ; i < 4; i++ )

{

//创建图片框

UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(x, 0, width, height)];

//创建图片数组

arr = @[[UIImage imageNamed:@"1.jpg"],[UIImage imageNamed:@"2.jpg"],[UIImage imageNamed:@"3.jpg"],[UIImage imageNamed:@"4.jpg"]];

//将图片添加到图片框上

imgView.image = arr[i];

//将图片框添加到滚动视图上

[scroll addSubview:imgView];

//叠加

x += width;

}

//设置滚动视图的大小

scroll.contentSize = CGSizeMake(width * 4, height);

//去掉弹簧效果

scroll.bounces = NO;

//隐藏滚动条

scroll.showsHorizontalScrollIndicator = NO;

//设置按页滚动

scroll.pagingEnabled = YES;

scroll.delegate = self;

//将滚动视图添加到视图上

[self.view addSubview:scroll];

//创建分页控件

p = [[UIPageControl alloc]initWithFrame:CGRectMake((width - 50)/2, 680, 100, 30)];

//设置页码个数

p.numberOfPages = 4;

//设置页码初始页

p.currentPage = 0;

//设置页码颜色

p.pageIndicatorTintColor = [UIColor redColor];

//设置当前页码的颜色

p.currentPageIndicatorTintColor = [UIColor cyanColor];

//将分页控件添加到视图上

[self.view addSubview:p];

//记录当前页面的图片页数

pagecount = p.currentPage;

//创建定时器

timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(scroll) userInfo:nil repeats:YES];

}

//滚动方法

-(void)scroll

{

pagecount++;

if (pagecount >= arr.count)

{

pagecount = 0;

}

//设置滚动视图的偏移量

[scroll setContentOffset:CGPointMake(pagecount * scroll.frame.size.width, 0) animated:YES];

}

//在滚动的时候调用此方法

-(void)scrollViewDidScroll:(UIScrollView *)scrollView

{

//当前的偏移量

CGPoint point = scrollView.contentOffset;

//获取当前所在的位置

p.currentPage = point.x / scrollView.frame.size.width;

//创建立即体验按钮

UIButton *btn = [[UIButton alloc]init];

//判断滚动到第四页的时候 停止计时器 显示立即体检按钮

if (p.currentPage == 3)

{

//停止定时器

[timer invalidate];

btn.frame = CGRectMake(110, 600, 200, 40);

//设置按钮背景颜色

btn.backgroundColor = [UIColor clearColor];

//设置边框

btn.layer.borderWidth = 1;

btn.layer.backgroundColor = [UIColor greenColor].CGColor;

[btn setTitle:@"立即体验" forState:UIControlStateNormal];

//设置文字颜色

[btn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];

//设置圆角

btn.layer.cornerRadius = 8;

btn.layer.masksToBounds = YES;

//给按钮添加点击事件

[btn addTarget:self action:@selector(anniu) forControlEvents:UIControlEventTouchUpInside];

//将按钮添加到视图上

[self.view addSubview:btn];

//设置禁止用户交互

scrollView.userInteractionEnabled = NO;

}

}

-(void)anniu

{

NSLog(@"走起");

}

//隐藏状态栏

-(BOOL)prefersStatusBarHidden

{

return YES;

}

@end

你可能感兴趣的:(滚动视图)