经验之谈—父子控制器(验证苹果的一句话)

40 篇文章 0 订阅

苹果官方有一句话说的非常好:当控制器的view互为父子关系,那么控制器最好也互为父子关系

我之前有一篇博客说控制器view的显示里边我说了一个很严重的问题,就是当控制的view还在,但是控制器不在了,造成了数据无法显示的问题,所以我们就要想办法保住控制器的命。那么我们今天继续来看一下,如何保住控制器的命。


  • 今天我们来用屏幕旋转的一个案例来说明一个问题:当控制器的view互为父子关系的时候,控制器不是父子关系时,会出现什么严重的问题。
  • 看一个案例,在ipad开发中,屏幕旋转是经常要发生的事情,因为屏幕比较大。
@interface ZYViewController ()
- (IBAction)vc1;

@property (nonatomic, strong) ZYOneViewController *one;

@end

@implementation ZYViewController

- (ZYOneViewController *)one
{
    if (!_one) {
        self.one = [[ZYOneViewController alloc] init];
        self.one.view.frame = CGRectMake(10, 70, 300, 300);
    }
    return _one;
}
- (void)viewDidLoad
{
    [super viewDidLoad];

}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    NSLog(@"willRotateToInterfaceOrientation");
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    NSLog(@"didRotateFromInterfaceOrientation");
}

- (IBAction)vc1 {

    [self.view addSubview:self.one.view];
}

这里,我们先通过懒加载一个ZYOneViewController,然后用一个属性对他强引用,保护他的命。然后我们监听ZYViewController的屏幕旋转事件。接下来我们在ZYOneViewController中也监听一下屏幕旋转事件:

@implementation ZYOneViewController


- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    NSLog(@"ZYOneViewController--willRotateToInterfaceOrientation");
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    NSLog(@"ZYOneViewController--didRotateFromInterfaceOrientation");
}

- (IBAction)oneBtnClick {
    NSLog(@"oneBtnClick");
}

然后我们看一下打印的屏幕旋转 ,打印的结果:
父子控制器

可以很明显的看出来,这当ZYViewController控制旋转的时候,ZYOneViewController控件并不知道。因为他们控制器之间,不是父子关系,那么不是父子关系,ZYViewController控制器旋转,凭什么告诉ZYOneViewController控制器,对吧。


那现在我们让他们成为父子关系,然后看一下结果:

@implementation ZYViewController

- (ZYOneViewController *)one
{
    if (!_one) {
        self.one = [[ZYOneViewController alloc] init];
        self.one.view.frame = CGRectMake(10, 70, 300, 300);

        [self addChildViewController:self.one];
    }
    return _one;
}

然后我们看一下旋转的结果:
父子控制器
所以我们要记得,当控制器的view互为父子关系,那么控制器最好也互为父子关系

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值