ScrollView滑动图片监听UIPageControl

来源:互联网 发布:手机淘宝无法提交订单 编辑:程序博客网 时间:2024/05/22 08:29
//图片#define Count 9@interface XiangViewController (){    UIPageControl *_pageControl;    UIScrollView *_scroll;}@end@implementation XiangViewController- (void)viewDidLoad{    [super viewDidLoad];   //1 先创建scrollView UIScrollView *scroll = [[UIScrollView alloc] init];//    scroll.frame = self.view.bounds;    scroll.frame = CGRectMake(0, 100, 320, 300);    [self.view addSubview:scroll];    _scroll = scroll;        //定义常量 scroll的高宽    CGFloat scrollWdith = scroll.frame.size.width;    CGFloat scrollHeight = scroll.frame.size.height;    //2 再创建ImageView    for (int i = 1; i <= Count; i++) {        //加载图片        NSString *imageName = [NSString stringWithFormat:@"%d.jpg",i];        UIImage *image = [UIImage imageNamed:imageName];        //创建UIimageView        UIImageView *imageview = [[UIImageView alloc]init];        imageview.image = image;        //x轴        CGFloat x = (i - 1)*scrollWdith;        imageview.frame = CGRectMake(x, 0, scrollWdith, scrollHeight);               //添加imageView        [scroll addSubview:imageview];            }        //3  设置滚动范围      scroll.contentSize = CGSizeMake(Count * scrollWdith, 0);        //隐藏水平滚动条    scroll.showsHorizontalScrollIndicator = NO;    //4 开启分页功能    scroll.pagingEnabled = YES;     //5 添加pageControl    UIPageControl *control = [[UIPageControl alloc] init];    control.bounds = CGRectMake(0, 0, 150, 50);    control.center = CGPointMake(scrollWdith * 0.5 , scrollHeight - 50);    //设置页数好控制点    control.numberOfPages = Count;        //选中当前颜色    control.currentPageIndicatorTintColor = [UIColor redColor];        //其他颜色    control.pageIndicatorTintColor = [UIColor blackColor];        [control addTarget:self action:@selector(pageChage) forControlEvents:UIControlEventValueChanged];            [self.view addSubview:control];    //获取当前的control    _pageControl = control;    //设置代理    scroll.delegate = self;}#pragma mark -  滑动页面  减速会调用- (void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView{    //获取当前页码       int page = scrollView.contentOffset.x / scrollView.frame.size.width;                //当前的control    _pageControl.currentPage = page;    }#pragma mark 点击pageControl- (void)pageChage{    CGFloat offsetX = _pageControl.currentPage * self.view.frame.size.width;//    [UIView beginAnimations:nil context:nil];    _scroll.contentOffset = CGPointMake(offsetX, 0);//    [UIView commitAnimations];}


原创粉丝点击