如果通过 selectedIndex 属性 更改,则更改视图时的动画将无法正常工作

Animation when changing views won't work properly if changed via selectedIndex property

为什么当我尝试通过 selectedIndex 更改视图时动画无法正常工作(黑屏)属性 但是如果我在点击 tabBar 项目时更改它们却可以正常工作?

(我是swift的初学者。不好意思说的太啰嗦了post,我想说得越清楚越好)

上下文

我想达到的目标:

我希望与 tabBar 项目 [0]、[1]、[n...] 相关联的视图具有演示动画,无论它们是在按下 tabBar 项目时发生变化还是 selectedItem 属性 发生变化以编程方式。


目前有效的方法:

我为 tabBar 定制了 class 并覆盖了 'shouldSelect viewController: UIViewController' 方法来放置动画。

每次按下 tabBar 项目时,动画效果都很好。它在 sourceView 上方显示了 destinationView,就像它在表演节目中一样。

extension MySubclassedTabBarController: UITabBarControllerDelegate  {

    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {

        if let sourceView = selectedViewController?.view, let destinationView = viewController.view, sourceView != destinationView {
            sourceView.superview?.insertSubview(destinationView, aboveSubview: sourceView)
            destinationView.transform = CGAffineTransform(translationX: sourceView.frame.size.width, y: 0)
            UIView.animate(withDuration: 0.25,
                           delay: 0.0,
                           options: .curveEaseInOut,
                           animations: { destinationView.transform = CGAffineTransform(translationX: 0, y: 0) },
                           completion: nil)
        }
        return true
    }
}

没有(正确)工作的地方:

除了在按下 tabBar 项目时更改视图外,我想通过在 UIButton 操作中以编程方式设置 selectedIndex 属性 来更改与 tabBar 关联的视图。

如果我第一次加载应用程序并尝试通过 alphaButton 更改视图,屏幕会变黑(sourceView 消失),然后显示动画 destinationView。

class FirstViewController () {

    @IBAction func alphaButton(_ sender: Any) {

        tabBarController?.selectedIndex = 1

        if let sourceView = view, let destinationView = tabBarController?.selectedViewController?.view, sourceView != destinationView {
            sourceView.superview?.insertSubview(destinationView, aboveSubview: sourceView)
            destinationView.transform = CGAffineTransform(translationX: sourceView.frame.size.width, y: 0)
            UIView.animate(withDuration: 0.25,
                           delay: 0.0,
                           options: .curveEaseInOut,
                           animations: { destinationView.transform = CGAffineTransform(translationX: 0, y: 0) },
                           completion: nil)
        }
    }
}

如果之前未呈现目标视图,转换将无法正常工作。

换句话说,它在以下情况下可以正常工作:

  1. 运行 应用
  2. 点击 tabBarItem[1](secondViewController)
  3. Return 通过点击 tabBarItem[0]
  4. 到 firstViewController
  5. 点击 alphaButton(它会再次将我发送到 secondViewController 并显示过渡,呈现前一个视图上方的视图,在本例中为 FirstViewController)

如果出现以下情况,它将无法正常工作:

  1. 运行 应用
  2. 点击 alphaButton(它显示过渡并呈现显示动画的视图,但屏幕先变黑)

为什么显示黑屏?我怎样才能避免这种情况?

欢迎以其他方式实现我想要的建议

谢谢:)

解决了。

使用这个(在 alphaButton 中):

destinationView.superview?.insertSubview(sourceView, belowSubview: destinationView)

而不是这个:

sourceView.superview?.insertSubview(destinationView, aboveSubview: sourceView)