Xcode self.navigationController.topViewController作为HomeViewController
我对将objective-c转换为swift有问题 对于我的火车,我改为swift,但在酒店: 目标-cXcode self.navigationController.topViewController作为HomeViewController,xcode,swift,casting,navigationcontroller,Xcode,Swift,Casting,Navigationcontroller,我对将objective-c转换为swift有问题 对于我的火车,我改为swift,但在酒店: 目标-c - (void)interactionBeganAtPoint:(CGPoint)point { // Very basic communication between the transition controller and the top view controller // It would be easy to add more control, support p
- (void)interactionBeganAtPoint:(CGPoint)point
{
// Very basic communication between the transition controller and the top view controller
// It would be easy to add more control, support pop, push or no-op
HASmallCollectionViewController *presentingVC = (HASmallCollectionViewController *)[self.navigationController topViewController];
HASmallCollectionViewController *presentedVC = (HASmallCollectionViewController *)[presentingVC nextViewControllerAtPoint:point];
if (presentedVC!=nil)
{
[self.navigationController pushViewController:presentedVC animated:YES];
}
else
{
[self.navigationController popViewControllerAnimated:YES];
}
}
Swift
func interactionBeganAtPoint(point: CGPoint) {
var presentingVC: HomeViewController! = (self.navigationController.topViewController as HomeViewController)
var presentedVC: HomeViewController! = (presentingVC.nextViewControllerAtPoint(point) as HomeViewController)
if (presentedVC != nil) {
self.navigationController.pushViewController(presentedVC!, animated: true)
} else {
self.navigationController.popViewControllerAnimated(true)
}
}
结果是(问题以粗体显示):
你有主意了吗?通过使用
作为
操作员,你告诉Swift你绝对确信你对HomeViewController
的下推会成功。但是,显然presentingVC.nextviewcontrollerpoint(point)
可以返回nil
,并且您无法成功地将nil
向下转换到HomeViewController
当向下转换可能失败时,使用as?
运算符返回您尝试向下转换到的类型的可选值
以下方面应起作用:
func interactionBeganAtPoint(point: CGPoint) {
let presentingVC = self.navigationController.topViewController as? HomeViewController
if let presentedVC = presentingVC?.nextViewControllerAtPoint(point) as? HomeViewController {
self.navigationController.pushViewController(presentedVC, animated: true)
} else {
self.navigationController.popViewControllerAnimated(true)
}
}
(我还使用了类型推断使代码更简洁;当Swift将
视为?HomeViewController
时,它发现presentingVC
的类型必须是HomeViewController?
。如果这很明显,我很抱歉。)我尝试了var presentingVC:HomeViewController!presentingVC=self.navController.topViewController作为HomeViewController打印LN(“presentingVC=(presentingVC)”)var presentedVC:HomeViewController!PresentDVC=PresentGVC?下一个可视控制器点(点)为?HomeViewController println(“PresentDVC=(PresentDVC)”)结果:presentingVC=PresentDVC=nil我不明白,为什么PresentDVC是nil!
func interactionBeganAtPoint(point: CGPoint) {
let presentingVC = self.navigationController.topViewController as? HomeViewController
if let presentedVC = presentingVC?.nextViewControllerAtPoint(point) as? HomeViewController {
self.navigationController.pushViewController(presentedVC, animated: true)
} else {
self.navigationController.popViewControllerAnimated(true)
}
}