#import "MainViewController.h"
#define Number 4
@interface MainViewController () <UIScrollViewDelegate>
//设置属性:
@property (nonatomic ,retain) UIScrollView *scroll;
@property (nonatomic ,retain) UIPageControl *page;
@property (nonatomic ,assign) NSInteger flag;
@end
@implementation MainViewController
//内存管理:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//建一个大的scrollView:
UIScrollView *scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(20, 20, 335, 585)];
scroll.contentSize = CGSizeMake(335*4, 0);
[self.view addSubview:scroll];
scroll.backgroundColor = [UIColor yellowColor];
scroll.pagingEnabled = YES;
scroll.delegate = self;
self.scroll = scroll;
self.scroll.bounces = YES;
[scroll release];
//控制翻页的UIPageControl
UIPageControl *page = [[UIPageControl alloc]initWithFrame:CGRectMake(20, 605, 335, 50)];
[self.view addSubview:page];
page.numberOfPages = 4;
self.page = page;
page.backgroundColor = [UIColor blackColor];
[page addTarget:self action:@selector(page:) forControlEvents:UIControlEventValueChanged];
[page release];
//使用循环创建小的UIScrollView,并加在大的上面
for (NSInteger i = 0; i < Number; i++) {
//创建小的scroll:
UIScrollView *scroll1 = [[UIScrollView alloc]initWithFrame:CGRectMake(335 * i, 0, 335, 585)];
scroll1.contentSize = CGSizeMake(0, 0);
[self.view addSubview:scroll1];
[scroll1 release];
scroll1.minimumZoomScale = 0.5;
scroll1.maximumZoomScale = 2;
scroll1.delegate = self;
[self.scroll addSubview:scroll1];
//给小的UIScrollView添加图片:
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 335, 585)];
NSString *name = [NSString stringWithFormat:@"%ld.jpg",
i+1];
UIImage *image = [UIImage imageNamed:name];
imageView.image = image;
[scroll1 addSubview:imageView];
[imageView release];
}
}
//实现小的UIScrollView放大缩小:
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
if (scrollView != _scroll) {
return [scrollView.subviews firstObject];
}
else
{
return nil;
}
}
//协议里减速完成方法里实现翻页后放大倍数还原
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
self.page.currentPage = self.scroll.contentOffset.x/335;
//方法一:
// for (UIScrollView *scroll in scrollView.subviews) {
//
// if ([scroll isKindOfClass:[UIScrollView class]]) {
// scroll.zoomScale = 1;
// }
// }
//方法二:
NSInteger index = _scroll.contentOffset.x/335;
_page.currentPage = index;
if (index != _flag) {
UIScrollView *scroll = [_scroll.subviews objectAtIndex:_flag];
scroll.zoomScale = 1;
_flag = index;
}
//实现相册的循环:
if (self.scroll.contentOffset.x >= 335 * 3) {
[_scroll setContentOffset:CGPointMake(0, 0) animated:NO];
self.page.currentPage = _scroll.contentOffset.x;
}
else if (self.scroll.contentOffset.x <= 0) {
[_scroll setContentOffset:CGPointMake(3*335, 0) animated:NO];
self.page.currentPage = _scroll.contentOffset.x;
}
}
//UIPage绑定的方法,控制翻页:
- (void)page:(UIPageControl *)page
{
[self.scroll setContentOffset:CGPointMake(page.currentPage * 335, 0) animated:YES];
}