#import "ViewController.h"
@interface ViewController ()<UIScrollViewDelegate>
{
UIPageControl *_pageControl;
UIScrollView *_scrollView;
}
@end
//宏定义view的宽和高
#define Mwidth self.view.frame.size.width
#define Mheight self.view.frame.size.height
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//----------------------------scrollView-----------------------------
_scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
//添加到视图
[self.view addSubview:_scrollView];
//添加图片
for (int i = 0; i < 5; i++) {
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, i*Mheight, Mwidth, Mheight)];
imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"scene%d.jpg", i+1]];
[_scrollView addSubview:imageView];
}
//总尺寸大小
_scrollView.contentSize = CGSizeMake(Mwidth, Mheight*5);
//分页属性打开
_scrollView.pagingEnabled = YES;
//反弹效果关闭
_scrollView.bounces = NO;
//设置代理,签署UIScrollViewDelegate协议
_scrollView.delegate = self;
//-----------------------pageControl-------------------
_pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, Mheight*7/8, Mwidth, Mheight/8)];
//非当前页的指示器颜色
_pageControl.pageIndicatorTintColor = [UIColor grayColor];
_pageControl.currentPageIndicatorTintColor = [UIColor redColor];
//添加页数控制器到视图
[self.view insertSubview:_pageControl aboveSubview:_scrollView];
//总页数
_pageControl.numberOfPages = _scrollView.subviews.count;
//添加事件方法
[_pageControl addTarget:self action:@selector(pageControlAction:) forControlEvents:UIControlEventValueChanged];
}
//实现pageControlAction
-(void)pageControlAction:(UIPageControl *)pageControl{
//显示的图片根据页数变化
_scrollView.contentOffset = CGPointMake(0,pageControl.currentPage * Mheight);
}
//实现代理方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
//页数随着显示的图片变化
_pageControl.currentPage = scrollView.contentOffset.y / Mheight;
}
@end
UIScrollView实现滑动图片
最新推荐文章于 2025-03-03 08:53:03 发布