UIScrollViewHomework--SimplePhot
做一个简易的相册, 每个图片都可以放大缩小,并且翻到第二张图时,再翻回来就变成原来的大小
//1.创建视图控制器RootViewController,并在Appdelegate.m中将其设为根视图控制器
RootViewController *rootVC = [[RootViewController alloc]init];
self.window.rootViewController = rootVC;
[rootVCrelease];
//2.在RootViewController.m中进行实现
#import "RootViewController.h"
//若要实现视图的缩放与翻回还原, 需要用到代理
@interface RootViewController () {
//将大滚动视图和其上小滚动视图元素的位置下标设为全局变量
UIScrollView *photoScollView;
NSInteger flag;
}
@end
@implementation RootViewController
- (void)viewDidLoad {
[superviewDidLoad];
//当前屏幕的大小
CGSizescreenSize = [UIScreen mainScreen].bounds.size;
//相片名字集合
NSArray*nameArray = @[@"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8",@"9", @"10", @"11", @"12", @"13", @"14", @"15",@"16", @"17", @"18", @"19", @"20", @"21", @"22", @"23",@"24"];
//元素下标起始为0
_flag =0;
//创建大的滚动视图
photoScollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0, screenSize.width, screenSize.height)];
photoScollView.contentSize = CGSizeMake(screenSize.width *nameArray.count, screenSize.height);
photoScollView.pagingEnabled = YES;
//为大滚动视图设置代理
photoScollView.delegate = self;
photoScollView.showsHorizontalScrollIndicator = NO;
[self.viewaddSubview:photoScollView];
[photoScollView release];
//通过for循环, 设置与相片数量相等的小滚动视图, 并将相片放到小滚动视图上
for(NSInteger i = 0; i < nameArray.count; i++) {
//创建小滚动视图
UIScrollView *smallScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(i * screenSize.width, 0, screenSize.width,screenSize.height)];
//缩放
smallScrollView.minimumZoomScale = 0.5;
smallScrollView.maximumZoomScale = 2;
smallScrollView.zoomScale = 1.0;
//为小滚动视图设置代理
smallScrollView.delegate = self;
[photoScollView addSubview:smallScrollView];
[smallScrollView release];
//创建相片视图
UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:nameArray[i]]];
imageView.frame = CGRectMake(0, 0, screenSize.width,screenSize.height);
//为相片视图设置tag值
imageView.tag = 100;
[smallScrollView addSubview:imageView];
[imageView release];
}
}
#pragma mark - UIScrollViewDelegate
//对哪个视图进行缩放
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
if(scrollView != photoScollView) {
return [scrollView viewWithTag:100];
} else{
return nil;
}
}
//视图结束拖拽时实现视图还原
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
if(scrollView == photoScollView) {
NSInteger currentPage = photoScollView.contentOffset.x / 375;
if (currentPage != flag) {
UIScrollView *smallScrollView = [photoScollView.subviewsobjectAtIndex:flag];
smallScrollView.zoomScale = 1.0;
flag = currentPage;
}
}
}
@end