在viewController.m里面
@interface ViewController ()
{
UIScrollView *scroll; //滚动视图
NSArray *imgArr; //图片数组
UIPageControl*page; //分页控件
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//设置背景颜色
self.view.backgroundColor= [UIColor cyanColor];
//创建滚动视图
scroll = [[UIScrollView alloc]initWithFrame:self.view.frame];
//设置代理
scroll.delegate=self;
//将滚动视图添加到视图上
[self.view addSubview:scroll];
// 创建图片数组
imgArr =@[@"1.jpg",@"2.jpg",@"3.jpg",@"4.jpg"];
//使用 for 循环设置图片
for(inti=0; i <4; 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= [UIImageimageNamed:imgArr[i]];
//允许与用户交互
imgView.userInteractionEnabled = YES;
//判断最后一张的时候显示立即体验按钮
if(i ==3)
{
//创建立即体验按钮
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame=CGRectMake((self.view.frame.size.width-100) /2,600,100,44);
[btnsetTitle:@"立即体验"forState:UIControlStateNormal];
//设置圆角
btn.layer.cornerRadius=8;
btn.layer.masksToBounds=YES;
//设置边框
btn.layer.borderWidth=1;
btn.layer.borderColor= [UIColorcyanColor].CGColor;
//添加点击事件
[btnaddTarget:self action:@selector(btn) forControlEvents:UIControlEventTouchUpInside];
//将按钮添加到视图上
[imgViewaddSubview:btn];
}
// 将图片框添加到滚动视图上
[scrolladdSubview:imgView];
}
//设置滚动范围
scroll.contentSize = CGSizeMake(self.view.frame.size.width *4, self.view.frame.size.height);
//取消弹簧效果
scroll.bounces=NO;
//设置分页滚动
scroll.pagingEnabled = YES;
//隐藏水平滚动条
scroll.showsHorizontalScrollIndicator = NO;
//创建分页控件
page= [[UIPageControlalloc]initWithFrame:CGRectMake((self.view.frame.size.width-100) /2,670,100,30)];
//设置页数
page.numberOfPages = 4;
//设置页码颜色
page.pageIndicatorTintColor = [UIColor blackColor];
//当前页码的颜色
page.currentPageIndicatorTintColor = [UIColor redColor];
//添加到视图上
[self.view addSubview:page];
}
//滚动视图的协议方法 当滚动结束的时候调用
- (void)scrollViewDidScroll:(UIScrollView*)scrollView
{
//将滚动的页数和滚动视图关联
page.currentPage = scroll.contentOffset.x / self.view.frame.size.width;
}
//点击立即体验按钮的方法
-(void)btn
{
NSLog(@"立即体验按钮");
}
@end
网友评论