条件绑定的初始化程序必须具有可选类型,而不是“UIView”
问题描述:
我最近下载了该项目并将其转换为最新的swift语法。我不明白为什么我继续得到错误“初始值设定条件结合必须有可选的类型,而不是‘UIView的’条件绑定的初始化程序必须具有可选类型,而不是“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)
}
)
}
答
这是因为containerView
属性不是一个可选类型,你可以在这里看到(这是从文档(命令+ LMB)采取UIViewControllerContextTransitioing
):
...
public protocol UIViewControllerContextTransitioning : NSObjectProtocol {
// The view in which the animated transition should take place.
@available(iOS 2.0, *)
public var containerView: UIView { get }
...
您可以在guard
声明之后放置错误的行。
只是将'let containerView = transitionContext.containerView'移出guard语句并将其放在'containerView.insertSubview(toVC.view,belowSubview:fromVC.view)之上' –