UI UIScrollView和UIPageControl的结合使用

<span style="font-size:18px;">- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIScrollView *scrollView=[[UIScrollView alloc]initWithFrame:self.view.bounds];
    scrollView.contentSize=CGSizeMake(320*5, 480);
    //把图片名放到数组
    NSArray *nameArr=[NSArray arrayWithObjects:@"1.jpg",@"2.jpg",@"3.jpg",@"4.jpg",@"5.jpg", nil];
    for (int i=0; i<nameArr.count; i++) {
        UIImage *img=[UIImage imageNamed:[nameArr objectAtIndex:i]];
        UIImageView *imgView=[[UIImageView alloc]initWithFrame:CGRectMake(i*320, 0, 320, 480)];
        imgView.image=img;
        [scrollView addSubview:imgView];
        [imgView release];
    }
    scrollView.pagingEnabled=YES;
    scrollView.delegate=self;
    [self.view addSubview:scrollView];
    [scrollView release];
    self.scrollView=scrollView;
    
    UIPageControl *pageControl=[[UIPageControl alloc]initWithFrame:CGRectMake(50, 400, 200, 50)];
    pageControl.numberOfPages=5;
    pageControl.currentPageIndicatorTintColor=[UIColor redColor];
    //添加事件
    [pageControl addTarget:self action:@selector(pageChanged:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:pageControl];
    [pageControl release];
    self.pageControl=pageControl;
}


- (void)pageChanged:(UIPageControl*)pageControl
{
    long currentPage=pageControl.currentPage;
    CGPoint offset=CGPointMake(currentPage*320, 0);
    //设置scrollView的偏移量
    self.scrollView.contentOffset=offset;
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.pageControl.currentPage=self.scrollView.contentOffset.x/320;
//    //获取偏移量
//    CGPoint offset=scrollView.contentOffset;
//    //计算页数
//    int pageCount=offset.x/320;
//    self.pageControl.currentPage=pageCount;
    
}

-(void)dealloc
{
    [_scrollView release];
    [_pageControl release];
    [super dealloc];
}
</span>

你可能感兴趣的:(UI UIScrollView和UIPageControl的结合使用)