ios代码添加UIViewController对应的view作为子控件

来源:互联网 发布:ap网络架构 编辑:程序博客网 时间:2024/05/16 15:44

项目代码分析https://github.com/thanklife/iosChangeViewcontroller

这是一个代码实现view的例子:主view上有4个控件:3个按钮和一个UIView类型的contentView,其中点击某一个按钮的时候,就会在contentView上添加子控件进行显示

#import <UIKit/UIKit.h>@interface MainViewController : UIViewController{    IBOutlet UIView *contentView;    IBOutlet UIButton *firstButton;    IBOutlet UIButton *secondButton;    IBOutlet UIButton *thirdButon;    UIViewController *currentViewController;}-(IBAction)onClickbutton:(id)sender;@end
源码部分可见到在xib中需要设置一下三个button的tag id;
#import "MainViewController.h"#import "FirstViewController.h"#import "SecondViewController.h"#import "ThirdViewController.h"@implementation MainViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];    if (self) {        // Custom initialization    }    return self;}- (void)didReceiveMemoryWarning{    // Releases the view if it doesn't have a superview.    [super didReceiveMemoryWarning];}#pragma mark - View lifecycleFirstViewController *firstViewController;SecondViewController *secondViewController;ThirdViewController *thirdViewController;- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view from its nib.    firstViewController=[[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil];    [self addChildViewController:firstViewController];    secondViewController=[[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];    [self addChildViewController:secondViewController];    thirdViewController=[[ThirdViewController alloc] initWithNibName:@"ThirdViewController" bundle:nil];    [self addChildViewController:thirdViewController];    [contentView addSubview:thirdViewController.view];    currentViewController=thirdViewController;}- (void)viewDidUnload{    [super viewDidUnload];}- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{    return (interfaceOrientation == UIInterfaceOrientationPortrait);}-(IBAction)onClickbutton:(id)sender{    if ((currentViewController==firstViewController&&[sender tag]==1)||(currentViewController==secondViewController&&[sender tag]==2) ||(currentViewController==thirdViewController&&[sender tag]==3) ) {        return;    }    UIViewController *oldViewController=currentViewController;    switch ([sender tag]) {        case 1:        {            NSLog(@"留言及回复");            [self transitionFromViewController:currentViewController toViewController:firstViewController duration:1 options:UIViewAnimationOptionTransitionCurlUp animations:^{            }  completion:^(BOOL finished) {                if (finished) {                    currentViewController=firstViewController;                }else{                    currentViewController=oldViewController;                }            }];}            break;        case 2:        {            NSLog(@"生日提醒");            [self transitionFromViewController:currentViewController toViewController:secondViewController duration:1 options:UIViewAnimationOptionTransitionCurlDown animations:^{            }  completion:^(BOOL finished) {                if (finished) {                  currentViewController=secondViewController;                }else{                    currentViewController=oldViewController;                }            }];        }            break;        case 3:        {            NSLog(@"好友申请");            [self transitionFromViewController:currentViewController toViewController:thirdViewController duration:1 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{            }  completion:^(BOOL finished) {                if (finished) {                     currentViewController=thirdViewController;                }else{                    currentViewController=oldViewController;                }            }];        }            break;        default:            break;    }}@end

三个子控件都是由UIViewController对应的xib的view形成的,三个子控件实现都一致,差别在于背景色不同和 lable 的文本内容不同。这里仅列出一个的代码

#import <UIKit/UIKit.h>@interface FirstViewController : UIViewController@end#import "FirstViewController.h"@implementation FirstViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];    if (self) {        // Custom initialization    }    return self;}- (void)didReceiveMemoryWarning{    // Releases the view if it doesn't have a superview.    [super didReceiveMemoryWarning];    // Release any cached data, images, etc that aren't in use.}#pragma mark - View lifecycle- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view from its nib.    debugMethod();}- (void)viewDidUnload{    [super viewDidUnload];    // Release any retained subviews of the main view.    // e.g. self.myOutlet = nil;    debugMethod();}- (void)viewWillAppear:(BOOL)animated {    [super viewWillAppear:animated];    debugMethod();}- (void)viewDidAppear:(BOOL)animated {    [super viewDidAppear:animated];    debugMethod();}- (void)viewWillDisappear:(BOOL)animated {    [super viewWillDisappear:animated];    debugMethod();}- (void)viewDidDisappear:(BOOL)animated {    [super viewDidDisappear:animated];    debugMethod();}- (void)willMoveToParentViewController:(UIViewController *)parent {    debugMethod();}- (void)didMoveToParentViewController:(UIViewController *)parent {    debugMethod();}- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{    // Return YES for supported orientations    return (interfaceOrientation == UIInterfaceOrientationPortrait);}@end

经过这个内容总结:

1、子控件中添加 的view 也可有UIViewController,据目前了解的情况,这里的controller初始化后要保存,不然addSubview方法之后,就会被释放;

2、在xib中对这些子控件UIView的属性 simulated metrics--》size要设置为Freeform,status bar top bar,bottom bar可以根据情况进行设置。

3、在执行[self addChildViewController:firstViewController];的时候会调用firstViewController 的- (void)willMoveToParentViewController:(UIViewController *)parent方法

4、在执行[contentView addSubview:thirdViewController.view];的时候会执行 -[ThirdViewController viewDidLoad];

5、当进行addChildViewController的几个view进行切换的操作的实现是- (void)transitionFromViewController:(UIViewController *)fromViewController toViewController:(UIViewController *)toViewController duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options animations:(void (^ __nullable)(void))animations completion:(void (^ __nullable)(BOOL finished))completion NS_AVAILABLE_IOS(5_0);

apple文档的注释内容为:

  This method can be used to transition between sibling child view controllers. The receiver of this method is
  their common parent view controller. (Use [UIViewController addChildViewController:] to create the
  parent/child relationship.) This method will add the toViewController's view to the superview of the
  fromViewController's view and the fromViewController's view will be removed from its superview after the
  transition completes. It is important to allow this method to add and remove the views. The arguments to
  this method are the same as those defined by UIView's block animation API. This method will fail with an
  NSInvalidArgumentException if the parent view controllers are not the same as the receiver, or if the
  receiver explicitly forwards its appearance and rotation callbacks to its children. Finally, the receiver
  should not be a subclass of an iOS container view controller. Note also that it is possible to use the
  UIView APIs directly. If they are used it is important to ensure that the toViewController's view is added
  to the visible view hierarchy while the fromViewController's view is removed.

这里实现的代码是:

            [self transitionFromViewController:currentViewController toViewController:firstViewController duration:1 options:UIViewAnimationOptionTransitionCurlUp animations:^{
            }  completion:^(BOOL finished) {
                if (finished) {
                    currentViewController=firstViewController;
                }else{
                    currentViewController=oldViewController;
                }
            }];


该方法的执行会让依次执行:

-[SecondViewController viewDidLoad]
-[ThirdViewController viewWillDisappear:]
-[SecondViewController viewWillAppear:]
-[SecondViewController viewDidAppear:]
-[ThirdViewController viewDidDisappear:]

5,这个代码部分添加 #define debugMethod() NSLog(@"%s", __func__)的宏定义,在 view 的一些方法里面添加后,非常有利于观察各个方法的调用顺序,这里经过观察就可以更好的进行代码的添加和实现了。



阅读全文
0 0