指定根视图:
-
- self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[RootViewController new]];
定义属性 - #import "RootViewController.h"
- #import "FirstViewController.h"
- #import "SecondTableViewController.h"
- @interface RootViewController ()<UIScrollViewDelegate>
- @property (nonatomic, strong) UISegmentedControl *segmentedControl;
- @property (nonatomic, strong) UIScrollView *scrollView;
- @property (nonatomic, strong) FirstViewController *firstVC;
- @property (nonatomic, strong) SecondTableViewController *secondTVC;
- @end
-
- @implementation RootViewController
创建实现: - - (void)viewDidLoad
- {
- [super viewDidLoad];
-
-
- self.automaticallyAdjustsScrollViewInsets = NO;
-
- self.segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"first", @"second"]];
- self.navigationItem.titleView = self.segmentedControl;
- [self.segmentedControl addTarget:self action:@selector(segmentedControlAction:) forControlEvents:UIControlEventValueChanged];
- self.segmentedControl.selectedSegmentIndex = 0;
-
-
- self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64)];
- [self.view addSubview:self.scrollView];
-
- self.scrollView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width * 2, [UIScreen mainScreen].bounds.size.height - 64);
- self.scrollView.pagingEnabled = YES;
- self.scrollView.bounces = NO;
-
-
- self.firstVC = [FirstViewController new];
- self.secondTVC = [[SecondTableViewController alloc] initWithStyle:UITableViewStylePlain];
-
- [self addChildViewController:self.firstVC];
- [self addChildViewController:self.secondTVC];
- self.firstVC.view.frame = CGRectMake(0, 0, self.scrollView.frame.size.width, CGRectGetHeight(self.scrollView.frame));
- self.secondTVC.view.frame = CGRectMake([UIScreen mainScreen].bounds.size.width, 0, self.scrollView.frame.size.width, CGRectGetHeight(self.scrollView.frame));
- [self.scrollView addSubview:self.firstVC.view];
- [self.scrollView addSubview:self.secondTVC.view];
-
-
- self.scrollView.delegate = self;
- }
分段控制器点击方法
- - (void)segmentedControlAction:(UISegmentedControl *)sender
- {
- [self.scrollView setContentOffset:CGPointMake(sender.selectedSegmentIndex * self.scrollView.frame.size.width, 0) animated:NO];
- }
-
- - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
- {
- NSInteger n = scrollView.contentOffset.x / scrollView.frame.size.width;
- self.segmentedControl.selectedSegmentIndex = n;
- }
first/和second分别为UIViewController和UITableViewController只设颜色即可看效果(这里不做创建)
最终效果:
有问题微博私信我.
原文地址:http://blog.csdn.net/qq_31810357/article/details/49611345