您的位置:首页 > 移动开发 > IOS开发

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

2016-08-18 11:47 281 查看
原理:

把分段控件定义在导航栏标题视图上,在通过分段控件的响应事件的选中索引加载各个控制器视图在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:

4000
[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


运行效果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息