首页 > 代码库 > ScrollView分栏视图分析

ScrollView分栏视图分析

技术分享

代码精华部分如下:

//1.添加scrollView  
 /* 1). 添加一个scrollView;
    2).创建关注、热门、附近三个控制器。
    3). 存储它们的名字到数组中,遍历并放到本控制器里。
    4).设置scrollView的contentSize.
    5).设置scrollview的偏移量。
    6).调用当停止动画的方法设置为当前的scrollView.(应该是停止拖拽的方法)*/
    NSArray *controls = @[@"STRFollowViewController",@"STRHotViewController",@"STRNearViewController"];
    for (NSInteger i = 0; i < controls.count; i++) {
        UIViewController *vc = [[NSClassFromString(controls[i])  alloc] init];
        vc.title = self.titleNames[i];
        [self addChildViewController:vc];
    }
    self.MainScrollView.contentSize = CGSizeMake(self.titleNames.count *[UIScreen mainScreen].bounds.size.width , 0);
    self.MainScrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
    [self scrollViewDidEndDecelerating:self.MainScrollView];
}
//2.设置代理
#pragma mark scrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self scrollViewDidEndScrollingAnimation:scrollView];
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    /**
     1. 获取宽度和高度,还要打开分页功能
     2. 获取索引值。
     3. 设置偏移量
     4. 设置viewframe,如没有加载过再加载,否则不返回
     5. 添加子控制器view到scrollview上*/
    NSInteger width = SCREEN_WIDTH;
    NSInteger height = SCREEN_HEIGHT;
    CGFloat offsetX = scrollView.contentOffset.x;
    
    NSInteger index = offsetX/width;
    [self.topView topViewWithIndex:index];
    UIViewController *vc = self.childViewControllers[index];
    if ([vc isViewLoaded]) return;
    vc.view.frame = CGRectMake(offsetX, 0, width, height);
    [self.MainScrollView addSubview:vc.view];
}
//3.添加topView

- (STRTopView *)topView{
    if (!_topView) {
        _topView = [[STRTopView alloc] initWithFrame:CGRectMake(0, 0, 200, 44) titleNames:self.titleNames tagBlock:^(NSInteger index) {
            [self.MainScrollView setContentOffset:CGPointMake(index *SCREEN_WIDTH, 0) animated:YES];
        }];
    }
    return _topView;
}

 

ScrollView分栏视图分析