【问题标题】:Why call presentViewController in the end of custom segue, it cause viewDidAppear to be called twice?为什么在自定义 segue 结束时调用 presentViewController 会导致 viewDidAppear 被调用两次?
【发布时间】:2016-04-01 16:10:14
【问题描述】:

在我的 UIStoryboardSegue 子类中,我在 perform 方法的末尾使用了 presentViewController,这会导致 viewDidAppear/viewWillAppear 被调用两次?

如何防止这种情况发生?

谢谢

当前代码:

override func perform() {

    // Assign the source and destination views to local variables
    let sourceView = sourceViewController.view as UIView!
    let destView = destinationViewController.view as UIView!

    // Get the screen width and height
    let screenWidth = UIScreen.mainScreen().bounds.size.width
    let screenHeight = UIScreen.mainScreen().bounds.size.height

    // Specify the initial position of the destination view
    destView.frame = CGRectMake(0.0, screenHeight, screenWidth, screenHeight)

    // Add the destination view to the window
    let window = UIApplication.sharedApplication().keyWindow
    window?.insertSubview(destView, aboveSubview: sourceView)

    // Animate the transition
    UIView.animateWithDuration(0.7, animations: { () -> Void in

        // Scale down the source view
        sourceView.transform = CGAffineTransformScale(sourceView.transform, 0.90, 0.90)

        }) { (Finished) -> Void in
    }

    UIView.animateWithDuration(1.0, delay: 0.2, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.7, options: .CurveEaseOut, animations: { () -> Void in

        destView.frame = CGRectOffset(destView.frame, 0.0, -screenHeight)

        }) { (finished) -> Void in

            self.sourceViewController.presentViewController(self.destinationViewController as UIViewController, animated: false, completion: nil)
    }
}

我现在看到,如果没有 presentViewController,新控制器在动画自定义 segue 之后很快就会被销毁。我明白我们为什么需要它。

【问题讨论】:

  • 当你在destination-VC的viewDidAppear中添加print("(unsafeAddressOf(self))")时,会打印出相同的地址吗?
  • 是的(而且很酷)。试了 3 次。
  • 好的,现在将运行 appcoda 代码,然后编辑我的答案

标签: ios view call viewwillappear


【解决方案1】:

viewDidAppear 被调用两次的原因是您首先将 viewcontroller 作为子视图插入到 keyWindow 中。 (触发 viewDidAppear)

然后呈现视图控制器。 (这也会触发 viewDidAppear)

这也给你的应用带来了一些副作用,因为你最终会得到一个 viewHierachy 像:

-- KeyWindow
---- FirstVC View
---- SecondVC View
---- UITransitionView (because of the presentVC)
------- SecondVC View

如果您想实现这种滑动/滚动转换,为什么不直接使用滚动视图并在其中包含子视图控制器?

对此的另一种解决方案是使用自定义转换并简单地调用 presentViewController 和自定义转换,如下所述:http://www.raywenderlich.com/113845/ios-animation-tutorial-custom-view-controller-presentation-transitions

【讨论】:

  • 好的,谢谢。但是为什么一个受人尊敬的网站在他们的教程中这样做呢?他们把presentViewController放在perform方法的末尾?
  • @Shay 你不能再不具体了^^请告诉使用该网站,以便我们可以检查我们自己的。
  • 能否提供链接?也许我把你的问题弄错了:)
  • 刚刚在我的代码中尝试了没有 presentViewController 并且在展开自定义 segue 中没有 dismissViewControllerAnimated。它崩溃了。为此,我们需要 presentViewController。
  • 添加代码和重要注释。还测试了appcoda代码,结果一样。
猜你喜欢
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
  • 2020-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多