Вы, кажется, пытаетесь вручную переключаться между дочерними контроллерами представления, но в то же время используете сегменты (которые выполняют свои собственные переходы для вас).Исключите переходы (кроме первоначального перехода, если вы используете раскадровку с «представлением контейнера») и просто вручную создайте экземпляры дочерних контроллеров представления, используя их идентификаторы раскадровки.Но не используйте segues, а затем попробуйте заменить контроллеры дочерних представлений в prepare(for:sender:)
.
Также, когда вы используете transition(from:to:duration:options:animations:completion:)
, вы не должны добавлять представления в представлениеиерархия себя.Этот метод делает это для вас (если вы не используете опцию showHideTransitionViews
, которая сообщает методу, что вы берете это на себя, что нам не нужно здесь делать).Аналогично, когда вы используете опцию transitionCrossDissolve
, вам также не нужно связываться с alphas.
Таким образом, используя фрагмент кода из той статьи, на которую вы ссылаетесь,Вы можете сделать:
class FirstViewController: UIViewController {
@IBOutlet weak var containerView: UIView! // the view for the storyboard's "container view"
@IBOutlet weak var redButton: UIButton! // a button to transition to the "red" child view controller
@IBOutlet weak var blueButton: UIButton! // a button to transition to the "blue" child view controller
// tapped on "transition to red child view controller" button
@IBAction func didTapRedButton(_ sender: UIButton) {
redButton.isEnabled = false
blueButton.isEnabled = true
let oldVC = children.first!
let newVC = storyboard!.instantiateViewController(withIdentifier: "RedStoryboardID")
cycle(from: oldVC, to: newVC)
}
// tapped on "transition to blue child view controller" button
@IBAction func didTapBlueButton(_ sender: UIButton) {
blueButton.isEnabled = false
redButton.isEnabled = true
let oldVC = children.first!
let newVC = storyboard!.instantiateViewController(withIdentifier: "BlueStoryboardID")
cycle(from: oldVC, to: newVC)
}
func cycle(from oldVC: UIViewController, to newVC: UIViewController) {
// Prepare the two view controllers for the change.
oldVC.willMove(toParent: nil)
addChild(newVC)
// Get the final frame of the new view controller.
newVC.view.frame = containerView.bounds
// Queue up the transition animation.
transition(from: oldVC, to: newVC, duration: 0.25, options: .transitionCrossDissolve, animations: {
// this is intentionally blank; transitionCrossDissolve will do the work for us
}, completion: { finished in
oldVC.removeFromParent()
newVC.didMove(toParent: self)
})
}
func display(_ child: UIViewController) {
addChild(child)
child.view.frame = containerView.bounds
containerView.addSubview(child.view)
child.didMove(toParent: self)
}
func hide(_ child: UIViewController) {
child.willMove(toParent: nil)
child.view.removeFromSuperview()
child.removeFromParent()
}
}
Это дает: