您的位置:首页 > 产品设计 > UI/UE

UIScrollView总结

2015-09-19 14:29 435 查看
学习了scrollView一个相册的案例来总结下。

相册起始是一个大的scrollView里面嵌套多个小的scrollView。大的scollView控制图片间的切换,小的scrollView控制图片的缩放。

//创建外面大的scrollView
UIScrollView *rootAlbum = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0,deviceWidth + 5, deviceHeight)];
rootAlbum.tag = 10;

//设置滚动的时候是否按页滚动
rootAlbum.pagingEnabled = YES;
rootAlbum.delegate = self;

//设置scrollView的内容框架坐标
rootAlbum.contentSize = CGSizeMake((deviceWidth + 5) * 4, deviceHeight);

//不显示水平滚动条
rootAlbum.showsHorizontalScrollIndicator = NO;

//在大的scrollView中添加小的scrollView和图片
for (int i = 0; i < 4; i ++) {
PhotoView *myPhoto = [[PhotoView alloc] initWithFrame:CGRectMake(i * (deviceWidth + 5), 0, deviceWidth, deviceHeight)];
NSString *photoName = [NSString stringWithFormat:@"%d.jpg",i + 1];
myPhoto.tag = i + 1;
myPhoto.photo.image = [UIImage imageNamed:photoName];
[rootAlbum addSubview:myPhoto];
// NSLog(@"%f",myPhoto.frame.origin.x);
}
[self.view addSubview:rootAlbum];
// Do any additional setup after loading the view, typically from a nib.
}

int current = 1;

//scrollView滚动中调用的方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
if(scrollView.tag == 10){
//contentOffset的起点坐标是原始scrollView的左下角那个点
NSLog(@"%f",scrollView.contentOffset.y);
}
}

//滚动结束调用的方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
int loc = scrollView.contentOffset.x / (deviceWidth + 5) + 1;
UIScrollView *currentView = (UIScrollView *)[self.view viewWithTag:current];

//当切换图片时,如果页面有缩放就还原
if (current != loc && currentView.zoomScale != 1) {
currentView.zoomScale = 1;
}
current = loc;
}


控制图片的scrollView

- (id) initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
self.delegate = self;
_photo = [[UIImageView alloc] initWithFrame:self.bounds];
self.showsHorizontalScrollIndicator = NO;

//设置最大缩放
self.maximumZoomScale = 2.5;
//设置最小缩放
self.minimumZoomScale = 0.5;

[self addSubview:_photo];

//创建双击事件,当双击图片时放大双击的位置
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapEvent :)];
doubleTap.numberOfTapsRequired = 2;
[self addGestureRecognizer:doubleTap];
}
return self;
}

- (void) doubleTapEvent : (UITapGestureRecognizer *) doubleTap{

//如果当前页面没有缩放双击则放大双击部位,如果有缩放则还原
if(self.zoomScale == 1 ){
[UIView animateWithDuration:0.5 animations:^{
CGPoint point = [doubleTap locationInView:self];

//以所点击位置为中心的长80宽80的矩形填充当前的scrollView
[self zoomToRect:CGRectMake(point.x - 40, point.y - 40, 80, 80) animated:YES];
}];
}else{
[UIView animateWithDuration:0.5 animations:^{
self.zoomScale = 1;
}];
}
}

//让代理对象实现下面的方法,返回需要缩放的视图控件
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
return _photo;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息