码迷,mamicode.com
首页 > 其他好文 > 详细

UIScorlView 循环滚动

时间:2016-03-08 13:26:07      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

- (void) createAdScrollView
{
    _view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 150)];
    [self.view addSubview:_view];
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 150)];
    _scrollView.delegate = self;
    // 设置scrollView的contentSize
    _scrollView.contentSize = CGSizeMake(WIDTH*(self.scrollViewDataArray.count+1), 0);
    _scrollView.pagingEnabled = YES;
    _scrollView.delegate = self;
    
    // 注意这里不需要add,因为在headerView时直接return _scrollView;
     [_view addSubview:_scrollView];
    
    for (int i=0; i<self.scrollViewDataArray.count+1; i++) {
        int y = i;
        if (y == self.scrollViewDataArray.count) {
            y = 0;
        }
        UIButton *button = [ZCControl createButtonWithFrame:CGRectMake(WIDTH*i, 0, WIDTH, 150) title:nil imageName:nil bgImageName:nil target:self method:@selector(buttonClick:)];
//        [button sd_setBackgroundImageWithURL:[NSURL URLWithString:self.scrollViewDataArray[y][@"image_path"]] forState:UIControlStateNormal]; placeholderImage:[UIImage imageNamed:@"recommend_Face"];
        button.tag = 100+i;
        [_scrollView addSubview:button];
    }
    // 添加定时器
    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerClick) userInfo:nil repeats:YES];
    
    
    // 添加小白点
    pageController = [[UIPageControl alloc]initWithFrame:CGRectMake(100, 120, 100, 30)];
    pageController.numberOfPages = self.scrollViewDataArray.count;
    
    // 白色看不清设置成其他颜色
    pageController.pageIndicatorTintColor = [UIColor grayColor];
    
    // pageController虽然是和scrollView并用的,但是并不加载在sc
    [_view addSubview:pageController];
    
    // kvo观察者模式,负责观察某一个对象其中某一个值的变化,如果有新值变化就通知你。需要注意的是,观察者模式需要手动销毁,当前界面销毁并不代表观察者模式也销毁了
    // sc观察的对象,self为响应的对象,path为观察sc其中的一个属性,使用字符串来表示这个属性,要求与属性名保持一致。options为观察值变化为有新的变化的时候,通知我。context上下文
    
    [_scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)timerClick{
    // 首先判断_scrollView当前的偏移
    CGPoint point = _scrollView.contentOffset;
    point.x = point.x+WIDTH;
    
    [UIView animateWithDuration:1 animations:^{
        _scrollView.contentOffset = point;
    }completion:^(BOOL finished) {
        CGPoint point1 = _scrollView.contentOffset;
        if (_scrollView.contentOffset.x/WIDTH == self.scrollViewDataArray.count) {
            _scrollView.contentOffset = CGPointZero;
        }
    }];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    // keyPath为观察的那个key也就是属性,object为观察的的那个对象,change为变化的值
    int x = _scrollView.contentOffset.x/320;
    pageController.currentPage = x;
}

 

UIScorlView 循环滚动

标签:

原文地址:http://www.cnblogs.com/Ganggang888/p/5253585.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!