我正在尝试将子视图添加到子视图控制器的视图中。按下按钮时会创建子视图控制器。父视图控制器位于导航控制器内。
-(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 :(得分:1)
我不太确定我是否理解正确,但我的猜测是你希望你的盘子位于视图的中心
(这就是我的理由:
我希望它们堆叠在一起,彼此居中并在子视图控制器中居中。)
所以看起来你应该简单地替换
x = self.view.center.x;
与
x = 0.5f * CGRectGetWidth(self.view.frame);
答案 1 :(得分:0)
我认为您需要在设置中心之前将平板添加到视图中。设置中心将根据其父级边界有效地设置视图框架,并且当您进行设置时,他们不会拥有父级。