一个控制器(UIViewController)中需要管理多个tableView,addChildViewController注意事项

有时候,一个控制器(UIViewController)中需要管理多个tableView,我们需要将多个控制器加入到主控制器中去。使用UIViewController的addChildViewController方法即可。但是这时可能会在tableView的位置上出现问题:

1、UIViewController的automaticallyAdjustsScrollViewInsets属性是会根据所在界面的status bar,navigationbar,tabbar的高度,自动调整scrollView的insets。一般我们会将该属性设置为NO,手动管理布局。

  在ViewDidLoad中设置self.automaticallyAdjustsScrollViewInsets = NO;

2、这时添加进去的tableView的frame的Y值为0,会隐藏64的位置,我们需要在添加子控制器的tableView的时候,设置tableView的contentInset与scrollIndicatorInsets的距离顶部和底部的距离:

  vc.tableView.contentInset = UIEdgeInsetsMake(64,0,self.tabBarController.tabBar.height,0);

  // 设置滚动条的内边距

  vc.tableView.scrollIndicatorInsets = vc.tableView.contentInset;

  此处的64即导航条的高度,距离底部的高度是self.tabBarController.tabBar.height(49)

3、另外,我们需要创建一个scrollView来包含所有的tableView,控制各个tableView的显示。

  

#pragma mark - 懒加载

- (UIScrollView *)scrollView

{

    if (!_scrollView) {

        _scrollView = [[UIScrollView alloc]init];

        _scrollView.frame = self.view.bounds;

        _scrollView.delegate = self;

        _scrollView.pagingEnabled = YES;

        _scrollView.contentSize = CGSizeMake(_scrollView.width * self.childViewControllers.count, 0);

  // 添加默认的控制器

        [self scrollViewDidEndScrollingAnimation:_scrollView];

    }

    return _scrollView;

}

 

#pragma mark - UIScrollViewDelegate

// scrollView停止滑动时调用:非手动拖动时调用

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView

{

    NSInteger index = scrollView.contentOffset.x / scrollView.width;

    UITableViewController *controller = self.childViewControllers[index];

    controller.view.frame = CGRectMake(scrollView.contentOffset.x, 0, screenW, scrollView.height);

    controller.tableView.contentInset = UIEdgeInsetsMake(64, 0, self.tabBarController.tabBar.height, 0);

    controller.tableView.scrollIndicatorInsets = controller.tableView.contentInset;

     [scrollView addSubview:controller.view];

}

// scrollView停止滑动时调用:手动滑动时调用

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView

{

    [self scrollViewDidEndScrollingAnimation:scrollView];

}

posted on 2016-11-01 08:49  lrjdaml  阅读(200)  评论(0编辑  收藏  举报