2015-05-22 282 views
0

我想將子視圖添加到子視圖控制器的視圖。子視圖控制器是在按下按鈕時創建的。父視圖控制器在導航控制器內。iOS - 將子視圖添加到子視圖控制器視圖

-(void)weightPlatePressed:(id)sender { 

    NSInteger week = self.weekControl.selectedSegmentIndex + 1; 
    NSInteger set = self.setControl.selectedSegmentIndex + 1; 
    NSInteger max = [self.weightTextField.text integerValue]; 

    NSInteger weight = [KFLiftCalculator weightForWeek:week andSet:set fromMax:max]; 

    if (weight <= 0) { 
     return; 
    } 

    KFWeightPlateViewController * vc = [[KFWeightPlateViewController alloc] init]; 
    vc.delegate = self; 

    if (self.outputUnitControl.selectedSegmentIndex == 0) { 
     vc.weightPlatesArray = [KFLiftCalculator plateCountsInPoundsWeight:weight]; 
     vc.isPoundsUnit = YES; 
    } else { 
     vc.weightPlatesArray = [KFLiftCalculator plateCountsInKilosForWeight:weight]; 
     vc.isPoundsUnit = NO; 
    } 

    [self addChildViewController:vc]; 
    CGFloat width = self.view.frame.size.width * 0.8; 
    vc.view.frame = CGRectMake(1, 1, width, width * 1.2); 
    vc.view.center = self.view.center; 
    [self.view addSubview:vc.view]; 
    [vc didMoveToParentViewController:self]; 
} 

在子視圖控制器我嘗試,但未能通過調用下面的方法正確定位子視圖的viewWillLayoutSubviews方法。

-(void)addPoundWeightPlates { 

    UILabel * currentPlate = nil; 
    UILabel * previousPlate = nil; 

    const CGFloat scaleFactor = (self.view.frame.size.width/40); 
    const CGFloat bottomPadding = 10; 

    for (NSInteger i = 0; i < [self.weightPlatesArray count]; i++) { 

     NSInteger numberOfPlates = [[self.weightPlatesArray objectAtIndex:i] integerValue]; 

     if (numberOfPlates > 0) { 

      for (NSInteger j = 0; j < numberOfPlates; j++) { 

       currentPlate = [KFWeightPlate poundWeightPlateNumber:i scaleFactor:scaleFactor]; 

       CGFloat x, y; 

       if (previousPlate == nil) { 
        y = self.view.frame.size.height - bottomPadding - (currentPlate.frame.size.height/2); 
       } else { 
        y = previousPlate.center.y - (previousPlate.frame.size.height/2) - (currentPlate.frame.size.height/2); 
       } 

       x = self.view.center.x; 
       currentPlate.center = CGPointMake(x, y); 
       [self.view addSubview:currentPlate]; 
       previousPlate = currentPlate; 
      } 
     } 
    } 
} 

子視圖的標籤,它們會添加到子視圖控制器的看法,但他們的位置不正確,我想不通爲什麼。我希望它們堆疊在一起,彼此居中並以子視圖控制器爲中心。它們彼此堆疊並彼此居中,但它們不位於子視圖控制器中。

我試圖按照guide provided by Apple,並在網上尋找其他地方,但我無法弄清楚。

+0

如何您板最終被解僱了? x確定嗎? – dave234

+0

x值是給我的問題。 y值完美運作。 – KevinF

回答

1

不太清楚我理解正確的,你的,但我的猜測是,你要設在視圖的中心,您板

(這就是驅使我在這裏:

我希望他們堆放在彼此的頂部,在彼此的中心,並在子視圖控制器中心)。

所以看起來你應該只需更換

x = self.view.center.x; 

x = 0.5f * CGRectGetWidth(self.view.frame); 
0

我認爲你需要在設置它們的中心之前將板添加到你的視圖中。設置中心將有效地設置視圖框架的相對於其父界的邊界,並且在設置時它們沒有父視圖。

+0

不幸的是,在設置中心之前將板添加到視圖中並不能解決問題。 – KevinF

相關問題