程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C >> 關於C >> 經驗之談—父子控制器(驗證蘋果的一句話)

經驗之談—父子控制器(驗證蘋果的一句話)

編輯:關於C

蘋果官方有一句話說的非常好:當控制器的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互為父子關系,那麼控制器最好也互為父子關系

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved