条件绑定的初始化程序必须具有可选类型,而不是" UIView"

时间:2016-10-11 03:55:24

标签: swift3

我最近下载了这个项目并将其转换为最新的swift语法。我无法理解为什么我继续得到错误"条件绑定的初始化程序必须具有可选类型,而不是" UIView"

在线发生错误:

let containerView = transitionContext.containerView

以下是完整代码:

func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
    guard
        let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from),
        let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to),
        let containerView = transitionContext.containerView
        else {
            return

    }

    containerView.insertSubview(toVC.view, belowSubview: fromVC.view)

    let screenBounds = UIScreen.main.bounds
    let bottomLeftCorner = CGPoint(x: 0, y: screenBounds.height)
    let finalFrame = CGRect(origin: bottomLeftCorner, size: screenBounds.size)

    UIView.animate(
        withDuration: transitionDuration(using: transitionContext),
        animations: {
            fromVC.view.frame = finalFrame
        },
        completion: { _ in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        }
    )
}

1 个答案:

答案 0 :(得分:0)

这是因为containerView属性不是可选类型。正如您在此处看到的(取自UIViewControllerContextTransitioing上的文档(命令+ LMB)

...
public protocol UIViewControllerContextTransitioning : NSObjectProtocol {


    // The view in which the animated transition should take place.

    @available(iOS 2.0, *)
    public var containerView: UIView { get }
...

您可以在guard声明之后放置错误的行。