2016-04-17 5 views
0

У меня есть встроенный контейнер на контроллере представления, и я хотел бы изменить его содержимое в зависимости от конкретного условия. Как мне это сделать, зная, что может быть только один встроенный segue, связанный со встроенным контейнером.Как программно выбрать контроллер встроенного представления?

Я попытался установить контроллер просмотра между моим встроенным контейнером и двумя возможными видами контента, но он не будет работать из-за пользовательских segues (ошибка: «Не удалось создать segue с классом« null »). Не понимаю эту ошибку, если кто-то может рассказать мне больше об этом :)

Я прочитал несколько способов обойти эту проблему, создав представление в виде табуляции и переключение между вкладками программно или добавив 2 вид контейнера и скрытие нежелательных один, но это, кажется, своего рода Hacky.

что бы наилучшая практика, чтобы сделать это? (Свифт пожалуйста)

Благодарим за помощь

ответ

1

Существует два способа сделать это: сначала добавьте два вида контейнера друг на друга и установите альфа-значение 0 для одного и 1 для другого и переключите альфа-значения, когда вы хотите изменить между контроллерами представлений. Недостатком этого является то, что всегда будут созданы два контроллера представлений. Второй способ - изменить тип segue от встраивания в пользовательский сегмент (это позволит вам добавить более одного сегмента в раскадровку), который загружает или заменяет контроллер вида. Вот реализация реализованного мной segue, который делает это, если вы его понимаете, вы можете реализовать его быстро.

(void)perform 
// 
// Used to seque between the master view controller and its immediate child view controllers and also from the homw view controller 
// and all its immediate child controllers. 
// At app launch then it is necessary to directly load a particular view controller - this is determined by checking that the source 
// view controller has no children. At other times the seque is used to switch from one controller to another. 
// 
{ 

    // 
    // This seque is for use when there is a container view controller where it is necessary to switch the contained view controllers (storyboards only permit one embed seque). 
    // 
    // 
    //        embed segue        segueA 
    //    MainVC --------------------------> ContainerVC -------------------> VCA 
    //  (has the view containing 
    //  the containded VC) 
    //                  sequeB 
    //                --------------------> VCB 
    // 
    // 
    // When the app initially launches the OS will automatically execute the embed seque and thus the ContainerVC gets the opportunity in its viewDidLoad to decide which 
    // VC to load at that point and then execute either segueA or sequeB. Assuming it calls sequeA then when the seque executes the source will be the ContainerVC and the 
    // destination with will VCA. The seque checks to see if the containerVC already has any children, if not then it knows to just add VCA as a child. 
    // 

    DDLogInfo(@"SEGUE - entered seque"); 
    UIViewController *container = self.sourceViewController; 
    UIViewController *destination = self.destinationViewController; 
    if([container.childViewControllers count] == 0) 
    { 
     DDLogInfo(@"SEGUE - adding intitial VC: %@", [destination description]); 
     // The containerVC doesn't yet any any children so just add the destination VC as a child 
     [container addChildViewController:destination]; 
     destination.view.frame = container.view.frame; 
     [container.view addSubview:destination.view]; 
     [destination didMoveToParentViewController:container]; 
    } 
    else 
    { 
     // The containerVC already has an existing child and thus it is necessary to swap it out and replace it with the new child 
     UIViewController* currentChild = container.childViewControllers[0]; 

     currentChild.view.userInteractionEnabled = NO; 
     PyngmeAssert([container.childViewControllers count] == 1, @"More than one child controller"); 

     // First check to make sure the destination type is not the same as the current child 
     if([destination isMemberOfClass: [currentChild class]]) 
     { 
      DDLogInfo(@"SEGUE: Trying to swap view controllers of the same type *****"); 
     } 
     else 
     { 
      // Swap the new VC for the old VC 
      destination.view.frame = container.view.frame; 
      [currentChild willMoveToParentViewController:nil]; 
      [container addChildViewController:destination]; 

      [container transitionFromViewController:currentChild 
            toViewController:destination 
              duration:0.35 
              options:UIViewAnimationOptionTransitionCrossDissolve 
             animations:^{ 
             } 
             completion:^(BOOL finished) { 
              [currentChild removeFromParentViewController]; 
              [destination didMoveToParentViewController:container]; 
              DDLogInfo(@"SEGUE finished swapping seque"); 
             }]; 
     } 
    } 
} 
+0

Спасибо за ваш ответ. Я собираюсь попробовать альфа-метод, даже если он не может быть лучшим из них! – ypicard

Смежные вопросы