zoukankan      html  css  js  c++  java
  • 无限轮播器

    1.在sb中添加scrollView和pageControl. 或代码添加

          

      分页控制器的页数设置,和 分页控制器中'点'的颜色设置

          

    2.设置scrollView,并添加imageview   

        CGFloat imgW = 300;
        CGFloat imgH = 130;
        CGFloat imgY = 0;
        
        // 1.动态创建5个UIImageView加到UIScrollView中.  一共5页,#define IMAGECOUNT 5
        for (int i = 0; i < IMAGECOUNT; i++) {
            // 创建UIImageView
            UIImageView *imgView = [[UIImageView alloc] init];
            // 设置图片
            NSString *imgName = [NSString stringWithFormat:@"img_0%d",i];
            imgView.image = [UIImage imageNamed:imgName];
            // 设置frame
            CGFloat imgX = imgW * i;
            imgView.frame = CGRectMake(imgX, imgY, imgW, imgH);
            // 把UIImageView加到self.scrollView里面
            [self.scrollView addSubview:imgView];
        }
        
        // 2.设置UIScrollView的内容大小
        self.scrollView.contentSize = CGSizeMake(imgW * IMAGECOUNT, 0);
        
        // 3.实现分页,默认以self.scrollView的宽度来分页.
      self.scrollView.pagingEnabled = YES; // 4.隐藏滚动条 self.scrollView.showsHorizontalScrollIndicator = NO;

    3. 将pageControl和ScrollView相关联,需要设置UIPageControl的一些属性 

       // self.pageControl.numberOfPages = 5;//分页器的总页数
       // self.pageControl.currentPage = 0;//当前页

        //遵守协议

        @interface ViewController ()<UIScrollViewDelegate>

        //设置代理
        self.scrollView.delegate = self;
      
      //当scrollView滚动的时候调用
    - (void)scrollViewDidScroll:(UIScrollView *)scrollView
    {
        // 获取当前scrollView的contentOffset
        CGPoint point = scrollView.contentOffset;
        CGFloat scrollW = scrollView.frame.size.width;
      //当图片滚动超过半张时,让分页器显示下一页.所以+scrollW * 0.5
    int page = (point.x + scrollW * 0.5)/ scrollW; self.pageControl.currentPage = page; }

    4.添加定时器,实现自动滚动

    //每隔1s,调用nextImage方法,显示下一页
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
    // 显示下一页
    - (void)nextImage
    {
        // 1.获取当前的页数
        NSInteger page = self.pageControl.currentPage;
        
        // 判断是否滚到了最后一页
        if (page == self.pageControl.numberOfPages - 1) {
            page = 0;
        } else {
            page++;
        }
    
        // 2.根据当前要显示的页数,设置UIScrollView的contentOffset偏移量的X值
        CGFloat offSetX = page * self.scrollView.frame.size.width;
        
        // 3.设置contentOffset,进行滚动
        [self.scrollView setContentOffset:CGPointMake(offSetX, 0) animated:YES];
    }
  • 相关阅读:
    BF算法和KMP算法
    Python课程笔记 (五)
    0268. Missing Number (E)
    0009. Palindrome Number (E)
    0008. String to Integer (atoi) (M)
    0213. House Robber II (M)
    0198. House Robber (E)
    0187. Repeated DNA Sequences (M)
    0007. Reverse Integer (E)
    0006. ZigZag Conversion (M)
  • 原文地址:https://www.cnblogs.com/jiayongqiang/p/5556288.html
Copyright © 2011-2022 走看看