UIScrollView和UIPageControl结合实现简单图片浏览

来源:互联网 发布:淘宝优质标签卖家 编辑:程序博客网 时间:2024/05/22 06:33

初始化

#import <UIKit/UIKit.h>@interface RootView : UIView@property(retain,nonatomic)UIScrollView *bigscroll;@property(nonatomic,retain)UIPageControl *page;@end

    self.bigscroll=[[[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds] autorelease];    self.bigscroll.backgroundColor=[UIColor redColor];    self.bigscroll.contentSize=CGSizeMake([UIScreen mainScreen].bounds.size.width*8, [UIScreen mainScreen].bounds.size.height);        //分页    self.bigscroll.pagingEnabled=YES;        [self addSubview:self.bigscroll];    for (int i=0; i<8; i++) {        UIScrollView *sc=[[UIScrollView alloc] init];        //设置小scrollview的frame上        sc.frame=CGRectMake([UIScreen mainScreen].bounds.size.width*i, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);        //设置缩放比例        sc.minimumZoomScale=0.5;        sc.maximumZoomScale=2;        sc.tag=100+i;        [self.bigscroll addSubview:sc];                UIImageView *imv=[[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"h%d.jpeg",i+1]]];        imv.frame=sc.bounds;        [sc addSubview:imv];                }        self.page=[[UIPageControl alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height-50, [UIScreen mainScreen].bounds.size.width, 50)];    self.page.backgroundColor=[UIColor darkGrayColor];    self.page.numberOfPages=8;    [self addSubview:self.page];        
控制器里边

@interface CWViewController ()<UIScrollViewDelegate>@property(retain,nonatomic)RootView *rv;@property(retain,nonatomic)UIScrollView *tempScroll;@end

- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view.    self.rv.bigscroll.delegate=self;       [self.rv.page addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventTouchUpInside];    for (int i=0; i<8; i++) {        ((UIScrollView *)[self.rv.bigscroll viewWithTag:100+i]).delegate=self;    }     }

方法

-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{    //取小scrollVIew得子视图    //保存缩放视图    self.tempScroll=scrollView;    return [scrollView subviews][0];}-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{            NSLog(@"终于停了");    int i=self.rv.bigscroll.contentOffset.x/320;    self.rv.page.currentPage=i;     if (![self.tempScroll isEqual:[self.rv.bigscroll viewWithTag:100+i]]) {        self.tempScroll.zoomScale=1.0;            }        }-(void)pageAction:(UIPageControl *)sender{        NSLog(@"第%d页",sender.currentPage);      [UIView animateWithDuration:0.3 animations:^{        self.rv.bigscroll.contentOffset=CGPointMake(0+sender.currentPage*320, 0);    }];        if (![self.tempScroll isEqual:[self.rv.bigscroll viewWithTag:100+self.rv.bigscroll.contentOffset.x/320]]) {        self.tempScroll.zoomScale=1.0;            }            }



0 0