不确定这是否是一种奇怪的方法,但在Swift 3中我想检查一个对象是否是UIViewController
并且符合我的协议Transitionable
。我有:
guard let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to),
let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from),
let toTransitionable = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? Transitionable,
let fromTransitionable = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? Transitionable
else {
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
return
}
但是我希望我可以获得和UIViewController
和Transitionable
的对象和对象。
我尝试了let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? Transitionable as? UIViewController
,但这只是UIViewController
我也尝试过:
extension Transitionable where Self: UIViewController {
var viewController: UIViewController { return self }
}
但是当我拨打'Transitionable' is not a subtype of 'UIViewController'
例如
toTransitionable.viewController
transitionContext.containerView.addSubview(toTransitionable.viewController.view)
我知道我们可以在Swift 4中做as? (UIViewController & Transitionable)
但是这个项目将在Swift 3中进行
答案 0 :(得分:1)
我不确定这可能会有所帮助,但请尝试:
if let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? UIViewController{
if let _ = toViewController as? Transitionable{
print("conforms to protocol")
}
}
if let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? UIViewController{
if let _ = fromViewController as? Transitionable{
print("conforms to protocol")
}
}
或者,如果您只想在一个
的变量中使用它您可以创建一个扩展UIViewController并实现Transitionable协议的新类。
类似的东西:
class YourNewViewControllerClass : UIViewController,Transitionable{
//implements your Transitionable methods
}
后:
if let viewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? YourNewViewControllerClass{
//success
}