iOS-分段控件控制页面切换

来源:互联网 发布:淘宝售前和售后的区别 编辑:程序博客网 时间:2024/05/18 01:00

原理:
把分段控件定义在导航栏标题视图上,在通过分段控件的响应事件的选中索引加载各个控制器视图在self.view上

注意:要在AppDelegate中定义包含导航栏的入口,让ViewController继承导航栏控制器,分段控件不能作为导航栏的标题视图的

实现代码:
新建FirstViewController和SecondViewController两个控制器

AppDelegate.m文件的方法中加入口@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    //创建窗口    _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];    //背景颜色    _window.backgroundColor = [UIColor whiteColor];    //可视化    [_window makeKeyAndVisible];    ViewController *VC = [[ViewController alloc] init];    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:VC];    _window.rootViewController = nav;    return YES;}
#import "ViewController.h"#import "FirstViewController.h"#import "SecondViewController.h"@interface ViewController (){    FirstViewController *firstVC;    SecondViewController *secondVC;}@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    self.view.backgroundColor = [UIColor lightGrayColor];    UISegmentedControl *segmt = [[UISegmentedControl alloc] initWithItems:@[@"首页",@"第一个",@"第二个"]];    segmt.frame = CGRectMake(0, 0, 200, 50);    segmt.tintColor = [UIColor blueColor];    segmt.selectedSegmentIndex = 0;    [segmt addTarget:self action:@selector(segmtAction:) forControlEvents:UIControlEventValueChanged];    self.navigationItem.titleView = segmt;    firstVC = [[FirstViewController alloc] init];    secondVC = [[SecondViewController alloc] init];    firstVC.view.backgroundColor = [UIColor redColor];    secondVC.view.backgroundColor = [UIColor greenColor];}- (void) segmtAction:(UISegmentedControl *)segmt {    int index = (int)segmt.selectedSegmentIndex;    switch (index) {        case 0:            [firstVC.view removeFromSuperview];            [secondVC.view removeFromSuperview];            break;        case 1:            [self.view addSubview:firstVC.view];            [secondVC.view removeFromSuperview];            break;        case 2:            [self.view addSubview:secondVC.view];            [firstVC.view removeFromSuperview];            break;        default:            break;    }}@end

运行效果:
这里写图片描述

0 0