版权声明:本文为博主原创文章,未经博主允许不得转载。
指定根视图:
[objc] view plain copy
- // 设置window的根视图控制器
- self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[RootViewController new]];
定义属性
[objc] view plain copy
- #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
创建实现:
[objc] view plain copy
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // 适应scrollView
- 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;
- // 创建scrollView
- self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64)];
- [self.view addSubview:self.scrollView];
- // 设置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的子控制器
- [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];
- // 设置scrollView的代理
- self.scrollView.delegate = self;
- }
分段控制器点击方法
[objc] view plain copy
- - (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://weibo.com/hanjunqiang
原文地址:http://blog.csdn.net/qq_31810357/article/details/49611345
时间: 2024-11-02 11:04:57