UISegmentedControl切换页面

潘宪
2023-12-01
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:[[segmentedViewController alloc]init]];
    self.window.rootViewController=nav;
    return YES;
}
#import "segmentedViewController.h"

@interface segmentedViewController ()
@property(nonatomic, assign) UIViewController *first;
@property(nonatomic, assign) UIViewController *secend;
@end

@implementation segmentedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *segmentedData = [[NSArray alloc]initWithObjects:@"apple",@"orange",nil];
    UISegmentedControl *segmented=[[UISegmentedControl alloc]initWithItems:segmentedData];
    [segmented addTarget:self action:@selector(doSomethingInSegment:)forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView=segmented;

    UIViewController *first=[[UIViewController alloc]init];
    self.first=first;
    first.view.backgroundColor=[UIColor redColor];
    //first.view.frame=self.view.frame;
    [self addChildViewController:first];

    UIViewController *secend=[[UIViewController alloc]init];
    self.secend=secend;
    secend.view.backgroundColor=[UIColor blueColor];
    //secend.view.frame=self.view.frame;
    [self addChildViewController:secend];

}
-(void)doSomethingInSegment:(UISegmentedControl *)Seg
{
    NSInteger Index = Seg.selectedSegmentIndex;
    switch (Index) {
        case 0:
            self.first.view.frame=self.view.frame;
            [self.view addSubview:self.first.view];
            [self.first didMoveToParentViewController:self];
            break;

        default:
            self.secend.view.frame=self.view.frame;
            [self.view addSubview:self.secend.view];
            [self.secend didMoveToParentViewController:self];
            break;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
 类似资料: