【问题标题】:Initializer for conditional binding must have Optional type, not "UIView"条件绑定的初始化程序必须具有可选类型,而不是“UIView”
【发布时间】:2016-10-11 03:55:24
【问题描述】:

我最近下载了这个项目并将其转换为最新的 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)
        }
    )
}

【问题讨论】:

  • 只需将let containerView = transitionContext.containerView移出保护语句并将其放在containerView.insertSubview(toVC.view, belowSubview: fromVC.view)上方

标签: swift3


【解决方案1】:

这是因为containerView 属性不是可选类型。正如您在此处看到的(取自 UIViewControllerContextTransitioing 上的文档 (command + 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 语句之后。

【讨论】:

    猜你喜欢
    • 2019-03-11
    • 2017-01-22
    • 2018-03-25
    • 2016-01-08
    • 2017-04-08
    • 2016-09-23
    • 1970-01-01
    • 2017-09-19
    相关资源
    最近更新 更多