UIScrollView+UIPageControl 图片切换加分页标示

@interface ViewController : UIViewController<UIScrollViewDelegate>{
    UIScrollView *myScrollView;
    UIPageControl *myPageControl;
}
@property(nonatomic,strong) UIScrollView *myScrollView;
@property(nonatomic,strong) UIPageControl *myPageControl;
@implementation ViewController
@synthesize myScrollView;
@synthesize myPageControl;
- (void)viewDidLoad{
    [super viewDidLoad];
    //创建UIScrollView
    myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 30, 300, 188)];
    myScrollView.pagingEnabled = YES;//分页滚动
    //myScrollView.bounces = NO;//是否反弹
    myScrollView.showsHorizontalScrollIndicator = NO;
    myScrollView.delegate = self;
    [self.view addSubview:myScrollView];
    for (int i=1; i<=5; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d",i]]];
        imageView.frame = CGRectMake((i-1)*300, 0, 300, 188);
        [myScrollView addSubview:imageView];
    }
    CGSize size = CGSizeMake(300*5, 188);
    myScrollView.contentSize = size;
    //创建UIPageControl
    myPageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(110, 190, 100, 30)];
    myPageControl.numberOfPages = 5; //总的图片页数
    myPageControl.currentPage = 0;      //当前页
    [myPageControl addTarget:self action:@selector(pageTurn:) forControlEvents:UIControlEventValueChanged]; //用户点击UIPageControl的响应函数
    [self.view addSubview:myPageControl]; //将UIPageControl添加到主界面上。
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //更新UIPageControl的当前页
    CGPoint offset = scrollView.contentOffset;
    CGRect bounds = scrollView.frame;
    [myPageControl setCurrentPage:offset.x / bounds.size.width];
}

- (void)pageTurn:(UIPageControl*)sender
{
    //令UIScrollView做出相应的滑动显示
    CGSize viewSize = myScrollView.frame.size;
    CGRect rect = CGRectMake(sender.currentPage * viewSize.width, 0, viewSize.width, viewSize.height);
    [myScrollView scrollRectToVisible:rect animated:YES];
}
posted @ 2012-11-28 11:07  TQ.CH  阅读(444)  评论(0编辑  收藏  举报