这是一个用 UIScrollView 和 UIPageControl 还有代理模式 开发的一个简单的图片浏览器
先看一个图片缩放的例子
代码如下:主要实现的十图片的缩放 UiScrollView一个滚动显示的控件
@interface JMViewController ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *ScrollView;
@property (weak, nonatomic) IBOutlet UIImageView *imange;
@end
@implementation JMViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.ScrollView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);//设置ScrollView位置和大小
self.ScrollView.backgroundColor = [UIColor greenColor];
//设置滚动内容的范围, 这个比较重要, 是说明你得scrollview可以滚多远
self.ScrollView.contentSize = self.imange.image.size;
self.ScrollView.contentInset = UIEdgeInsetsMake(10, 0, 0, 10);
//设置滚动以后的留出的地方, 被滚得图片回不到以前的位置,(上,左,下,右):具体是按逆时针排列的:
self.ScrollView.delegate = self; //控制器是ScrollView的代理用来监听ScrollView
self.ScrollView.maximumZoomScale = 2.0; //设置图片的缩放比例
self.ScrollView.minimumZoomScale = 0.1;
}
//下面代理的简单演示
//当用户触碰到屏幕, self就会调用者这个方法,来告诉Scrollview,谁被触碰了,并把它缩放
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return _imange;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
NSLog(@"~~~~~~开始滑动~~~~~~~");
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
NSLog(@"!!!!!!!停止滑动!!!!!!!!!!");
}
@end
下面来看 图片浏览器
#import "JMViewController.h"
#define Kcontl 8 //定义宏 设置图片的张数
@interface JMViewController () <UIScrollViewAccessibilityDelegate>
{
UIPageControl *_pageControl;
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;
@end
@implementation JMViewController
- (void)viewDidLoad
{
[super viewDidLoad];
CGFloat h = self.view.frame.size.height;
CGFloat w = self.view.frame.size.width;
for (int i = 0; i < Kcontl; i++) {
UIImageView *imangeview = [[UIImageView alloc]init];//声明一个imangeview
imangeview.frame = CGRectMake(i*w, 0, w, h); //设置imangview大小与位置
NSString *imgname = [NSString stringWithFormat:@"0%d.jpg", i+1]; //获得图片名字
imangeview.image = [UIImage imageNamed:imgname];//把图片存入imangview
[self.scrollview addSubview:imangeview];//把imangview放到 scrllview中
}
//设置scrollew
_scrollview.contentSize = CGSizeMake(Kcontl*w, 0);
_scrollview.showsHorizontalScrollIndicator = NO;
_scrollview.pagingEnabled = YES;
_scrollview.delegate = self;// 给Scrolview设置代理
UIPageControl *pageControl = [[UIPageControl alloc] init];
pageControl.center = CGPointMake(w * 0.5, h - 20);
pageControl.bounds = CGRectMake(0, 0, 150, 50);
pageControl.numberOfPages = Kcontl; // 一共显示多少个圆点(多少页)
// 设置非选中页的圆点颜色
pageControl.pageIndicatorTintColor = [UIColor grayColor];
// 设置选中页的圆点颜色
pageControl.currentPageIndicatorTintColor = [UIColor blackColor];
// 禁止默认的点击功能
pageControl.enabled = NO;
[self.view addSubview:pageControl]; //加载到当前试图
_pageControl = pageControl;//记录pagecontreol
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//pageControl显示第几页是由用户滑动到宽度除以scrollview的宽度来计算的
int page = scrollView.contentOffset.x / scrollView.frame.size.width;
// 设置页码
_pageControl.currentPage = page;
}
@end