Встраивание массива UIViewController в UIViewController

Я пытаюсь встроить массив UIViewControllers в UIViewController с представлением UIViewControllers, имеющим определенные размеры и позиции в представлении UIViewController. Я обнаружил, что дочерние UIViewControllers с их представлением, отличным от происхождения (0, 0), не отображаются на экране. В родительском ViewController я добавил подпредставления для размещения этого коллажа дочерних контроллеров. В дочерних ViewController становится очевидным, что кадры просмотра имеют смещение начала координат, объявленное в родительском ViewController. Я попытался ввести некоторые ограничения для верхнего/левого и размеров каждого дочернего представления, но это, похоже, не имеет значения. Все советы, которые я вижу по этой теме, похоже, показывают примеры только с одним дочерним контроллером представления.

- (void)viewWillAppear:(BOOL)animated
{
    NSUInteger i = 0;
    for(PlotInfo *plotinfo in _plot.plots)
    {
        switch([plotinfo.PlotType integerValue])
        {
            case SWPlotTypesScatterPlot:
            {
                NSUInteger index = [self indexInViewControllers:scatterPlotViewControllers ForPartition:[plotinfo.PartitionIndex integerValue]];
                if(index == NSNotFound)
                {
                    ScatterPlotViewController *scatterPlotViewController = (ScatterPlotViewController*)[storyboard instantiateViewControllerWithIdentifier:@"segueScatterPlotView"];
                    scatterPlotViewController.currentPlot = currentPlot;
                    scatterPlotViewController.delegate = self.delegateScatterPlot;
                    plotViewController = scatterPlotViewController;

                    [scatterPlotViewControllers addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:scatterPlotViewController, kViewController, plotinfo.PartitionIndex, kPartitionIndex, [NSMutableArray arrayWithObject:[NSNumber numberWithInteger:i]], kActiveIDs, nil]];

                    scatterPlotViewController.view.frame = [self frameForChildController:[plotinfo.PartitionIndex integerValue]];
                    [self.view addSubview:scatterPlotViewController.view];
                    [self addChildViewController:scatterPlotViewController];

                    [self initConstraintsToSubView:scatterPlotViewController.view];


    //                    scatterPlotViewController.view.frame = CGRectMake(0.0, 0.0, scatterPlotViewController.view.frame.size.width, scatterPlotViewController.view.frame.size.height);
                    }
                    else
                    {
                        NSMutableDictionary *dict = (NSMutableDictionary*)[scatterPlotViewControllers objectAtIndex:index];
                        NSMutableArray *newActiveIDs = [NSMutableArray arrayWithArray:(NSMutableArray*)[dict objectForKey:kActiveIDs]];
                        [newActiveIDs addObject:[NSNumber numberWithInteger:i]];
                        [dict setObject:newActiveIDs forKey:kActiveIDs];
                    }
                }
                    break;
    // ………….                
                default:
                    break;
            }
            i++;
        }

        if([scatterPlotViewControllers count] > 0)
        {
            for(NSDictionary *dict in scatterPlotViewControllers)
            {
                ScatterPlotViewController *scatterPlotViewController = (ScatterPlotViewController*)[dict objectForKey:kViewController];
                scatterPlotViewController.activeIDs = [NSArray arrayWithArray:(NSMutableArray*)[dict objectForKey:kActiveIDs]];
                [scatterPlotViewController didMoveToParentViewController:self];
            }
        }
        // ………….
        [self updateViewConstraints];
}

- (void)viewWillDisappear:(BOOL)animated
{
// ………..

    if([scatterPlotViewControllers count] > 0)
    {
        for(NSDictionary *dict in scatterPlotViewControllers)
        {
            ScatterPlotViewController *scatterPlotViewController = (ScatterPlotViewController*)[dict objectForKey:kViewController];
            [scatterPlotViewController willMoveToParentViewController:nil];
            [scatterPlotViewController.view removeFromSuperview];
            [scatterPlotViewController removeFromParentViewController];
        }
    }
//…………
    differentTypesOfPlots = nil;
    barChartViewControllers = nil;
    pieChartViewControllers = nil;
    polarPlotViewControllers = nil;
    scatterPlotViewControllers = nil;
}


- (CGRect)frameForChildController:(NSUInteger)partitionIndex
{
    CGRect frameRect = CGRectZero;
    if(partitionIndex < [plotPartitionInformation count])
    {
        PartitionCell *cell = (PartitionCell *)[plotPartitionInformation objectAtIndex:partitionIndex];
        CGFloat heightFactor = self.view.bounds.size.height / cell.refHeight;
        CGFloat widthFactor = self.view.bounds.size.width / cell.refWidth;
        frameRect = CGRectMake(cell.xorigin*widthFactor, cell.yorigin*heightFactor, cell.width*widthFactor, cell.height*heightFactor);
    }

    return frameRect;
}

- (NSUInteger)indexInViewControllers:(NSMutableArray*)array ForPartition:(NSUInteger)index
{
    return [array indexOfObjectPassingTest:
            ^BOOL(NSDictionary *dict, NSUInteger idx, BOOL *stop)
            {
                return [(NSNumber*)[dict objectForKey:@"PartitionIndex"] integerValue] == index;
            }
            ];
}

- (void)initConstraintsToSubView:(UIView*)childView
{
    childView.translatesAutoresizingMaskIntoConstraints = NO;
    //Leading
    NSLayoutConstraint *leading = [NSLayoutConstraint constraintWithItem:childView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1.0f constant:childView.frame.origin.x];

    //Bottom
    NSLayoutConstraint *top =[NSLayoutConstraint constraintWithItem:childView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0f constant:childView.frame.origin.y];

    //Height to be fixed for SubView same as AdHeight
    NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:childView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:0 constant:childView.frame.size.height];
    //Height to be fixed for SubView same as AdHeight
    NSLayoutConstraint *width = [NSLayoutConstraint constraintWithItem:childView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:0 constant:childView.frame.size.width];

    [self.view addConstraint:leading];
    [self.view addConstraint:top];
    [childView addConstraint:height];
    [childView addConstraint:width];
}

person swainwri    schedule 03.07.2016    source источник
comment
Эта работа полностью зависит от источника, установленного для ячейки. Координаты должны быть равны нулю относительно пространства родительского представления. Я не вижу определения соответствующей структуры, которая позволила бы мне узнать, как вы создали это исходное значение.   -  person Feldur    schedule 03.07.2016
comment
Исходные значения и размеры определяются в подпрограмме `- (CGRect)frameForChildController:(NSUInteger)partitionIndex`, эти размеры создаются из другого места в моем приложении, однако все размеры и источники учитываются, чтобы найти их в родительском self.view. границы и являются нулевыми относительными. В качестве проверки я сгенерировал UIImage, используя происхождение и размеры каждого дочернего представления, и результирующее изображение воспроизводит коллаж представлений, который я хотел бы видеть на экране.   -  person swainwri    schedule 04.07.2016


Ответы (1)


Кажется, что я определял фрейм графического подпредставления в моем дочернем представлении ViewControllers с дочерним фреймом self.view. Когда я меняю начало кадра графического подвида на (0,0), я решаю свою проблему.

person swainwri    schedule 04.07.2016