2015-05-22 40 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

相关问题