2013-08-19 46 views
1

我想創建兩個並排的視圖添加到我的viewcontroller的視圖。爲了避免重複代碼,我試圖編寫一個通用的方法爲我創建兩個視圖。但是,這段代碼並不適合我。 view1和view2都是ivars。iOS:創建兩個視圖的方法

- (void)viewWillAppear:(BOOL)animated { 
    [super viewWillAppear:animated]; 

    [self makeView:view1]; 
    [self makeView:view2]; 
} 

- (void)makeView:(UIView*)view { 
    CGRect frame = self.view.bounds; 
    frame.size.height = frame.size.height/2; 
    if (view == view2) { 
    frame.origin = CGPointMake(0, frame.size.height); 
    } 
    view = [[UIView alloc] initWithFrame:frame]; 
    [self.view addSubview:view]; 
} 

我認爲這個問題可能處理線視圖==視圖2,某種變量引用錯誤的。 view == view2總是計算爲true,所以view1從不出現。在代碼view1和view2的後面部分是零。

+0

什麼,具體是出錯了?它是否會拋出異常?崩潰?不顯示您的意見?配置錯誤的視圖?控制檯中的任何東西? – Tim

+0

==是一個指針引用。嘗試[view isEqual:view2] – acorc

+0

是從xib還是storyboard加載'view1'和'view2'?如果是這樣,只需設置其框架而不是分配新視圖。如果不是,他們是什麼(除了空指針,希望)? –

回答

1

讓我們一步一步找出答案。

首先,你viewWillAppear被調用,並view1view2都是nil,因爲你沒有將它們設置爲任何事情。

然後,你打電話給你的方法view1,這是nil,所以參數將是值nil

創建框架,然後讓你的if語句。參數(view)爲nil,正如我們之前所說的,和view2nil,因爲正如我們前面所說,它開始爲nil,我們還沒有將其設置爲任何事情。因此,view==view2爲真,因爲nil==nil爲真,並且您獲得了view2所需的原始幀。

然後,您將view設置爲一個新的UIView,並將其添加到子視圖中,該子視圖會添加視圖(即view2所需的視圖),但您仍未設置view1變量。

在此之後,你與view2做同樣的事情,它給你使用完全相同的框架另一種觀點認爲,因爲viewview1view2都還nil

爲了避免這種情況,實際上應該在該方法之外創建view1view2view1/2 = [[UIView alloc] init];),並且只需執行方法內的所有設置部分即可。

0

如果它們還沒有被分配,你會路過一個零指針兩個廠景和視圖2,然後針對零指針,這將永遠是真實的比較。運行時會看到if(nil == nil)。嘗試這樣的:

- (void)viewWillAppear:(BOOL)animated { 
    [super viewWillAppear:animated]; 

    view1 = [[UIView alloc] init]; 
    view2 = [[UIView alloc] init]; 

    [self makeView:view1]; 
    [self makeView:view2]; 
} 

- (void)makeView:(UIView*)view { 
    CGRect frame = self.view.bounds; 
    frame.size.height = frame.size.height/2; 
    if (view == view2) { 
    frame.origin = CGPointMake(0, frame.size.height); 
    } 
    [view setFrame:frame]; 
    [self.view addSubview:view]; 
} 
0

這是一個指針的問題。試試這個:

- (void)testExample 
{ 
    object = [NSObject new]; 
    NSLog(@"Address 1: %p", object); 
    [self method:object]; 
} 

- (void) method:(NSObject*) _object { 
    NSLog(@"Address 2: %p", _object); 
    _object = [NSObject new]; 
    NSLog(@"Address 3: %p", _object); 
    NSLog(@"Address 4: %p", object); 
} 

的輸出是一樣的東西

Address 1: 0xcb98ae0 
Address 2: 0xcb98ae0 
Address 3: 0x11060950 
Address 4: 0xcb98ae0 

因此首先要獲取對象的指針。然後在method:你得到相同的指針。但是,當您分配一個新對象並將其分配給_objectview時,指針會發生變化,因此您的ivars view1view2將保持零。

您必須首先分配視圖並進行佈局。