有三个view,分别为view1、view2、view3,通过UISegmentedControl进行三个view的切换。
- @interface UIViewDemoViewController : UIViewController {
- IBOutlet UIView *view1;
- IBOutlet UIView *view2;
- IBOutlet UIView *view3;
- }
- - (IBAction)switchViews:(id)sender;
- @end
在Interface Builder中分别建立三个view,关联到各自的输出口,每个view上的UISegmentedControl关联到switchViews:操作。
- - (void)viewDidLoad {
- [super viewDidLoad];
- [self.view addSubview:view1];
- [self.view addSubview:view2];
- [self.view addSubview:view3];
- }
- - (IBAction)switchViews:(id)sender{
- UISegmentedControl *segmentedControl = sender;
- [[NSNotificationCenter defaultCenter] postNotificationName:@"switchViews" object:[NSNumber numberWithInteger:[segmentedControl selectedSegmentIndex]]];
- }
接着,为UISegmentedControl控件建立一个处理类。
- @interface SegmentedControl : UISegmentedControl {
- IBOutlet UIView *view1;
- IBOutlet UIView *view2;
- IBOutlet UIView *view3;
- IBOutlet UIViewDemoViewController* viewController;
- }
- @end
将UISegmentedControl控件的Class改为刚创建的处理类:SegmentedControl,然后,将UISegmentedControl控件关联到四个输出口:view分别关联到刚创建的三个view上,viewController关联到File's Owner上。
- - (void)awakeFromNib{
- [[NSNotificationCenter defaultCenter] addObserver:self
- selector:@selector(switchViews:)
- name:@"switchViews"
- object:nil];
- }
- - (void)switchViews:(NSNotification*)notification{
- NSNumber *viewNumber = [notification object];
- NSInteger i = [viewNumber integerValue];
- [self setSelectedSegmentIndex:i];
- UIView *chosenView = nil;
- switch (i) {
- case 0:
- chosenView = view1;
- break;
- case 1:
- chosenView = view2;
- break;
- case 2:
- chosenView = view3;
- break;
- default:
- break;
- }
- if (chosenView) {
- [[viewController view] bringSubviewToFront:chosenView];
- }
- }
- - (void)dealloc{
- [super dealloc];
- [[NSNotificationCenter defaultCenter] removeObserver:self];
- }
代码可以到视图切换的动画效果进行下载。