iPhone开发——Segmented Control

Home / iOS MrLee 2015-6-6 3128

UISegmentedControl是一个横向的组件,由多部分组成,每一部分都是一个独立的按钮,一般用来切换视图的显示模式或者在几项之间做单选。
这个控件并不是用来实现多视图切换的,实际开发中也几乎不用它来做多视图切换,此博文仅为模拟多视图应用。
1、创建一个Empty Application工程,命名为:MultiView-Navigation,如下图


2、选中工程中的Group MultiView-Tab,然后按住CMD(Windows键)+N,新建视图控制器MainViewController,如下图


3、依照上步,新建视图控制器FirstViewController、SecondViewController
4、修改MainViewController.xib,添加一个ToolBar控件,一个Segmented Control 控件,两个Fixed Space Bar Button Item控件,如下:


5、修改FirstViewController.xib、SecondViewController.xib,各添加一个Label控件,如下:


6、修改AppDelegae类,AppDelegate.h如下:
//  AppDelegate.h  
//  MultiView-SegmentControl  
//  
//  Created by Zhang Yanguang on 12-11-21.  
//  Copyright (c) 2012年 MyCompanyName. All rights reserved.  
//  
  
#import   
#import "MainViewController.h"  
@interface AppDelegate : UIResponder   
  
@property (strong, nonatomic) UIWindow *window;  
  
@property (strong, nonatomic) MainViewController *mainViewController;   
@end  
7、下面开始编写代码,主要修改MainViewController类,MainViewController.h如下:
@synthesize window = _window;  
@synthesize mainViewController;  
  
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
{  
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];  
    // Override point for customization after application launch.  
      
    self.mainViewController = [[MainViewController alloc]initWithNibName:@"MainViewController" bundle:nil];  
    //设置根视图控制器  
    self.window.rootViewController = self.mainViewController;  
      
    self.window.backgroundColor = [UIColor whiteColor];  
    [self.window makeKeyAndVisible];  
    return YES;  
}  
MainViewController.m如下:
//
//  MainViewController.h
//  MultiView-SegmentControl
//
//  Created by Zhang Yanguang on 12-11-21.
//  Copyright (c) 2012年 MyCompanyName. All rights reserved.
//
#import 
#import "FirstViewController.h"
#import "SecondViewController.h"
@interface MainViewController : UIViewController{
    
}
@property(strong,nonatomic)FirstViewController *firstViewController;
@property(strong,nonatomic)SecondViewController *secondViewController;
@property(strong,nonatomic)IBOutlet UISegmentedControl *segmentControl;
@property(strong,nonatomic)IBOutlet UIToolbar *toolBar;
-(IBAction)changeView:(id)sender;
@end
注意,不要忘记设置输出口和操作与xib文件中控件与事件的连接,如下:


8、编译、运行,效果如下:


点击下载本文源代码

本文链接:https://www.it72.com/3104.htm

推荐阅读
最新回复 (0)
返回