gpt4 book ai didi

xcode - self.navigationController.topViewController 作为 HomeViewController

转载 作者:行者123 更新时间:2023-11-28 07:15:16 32 4
gpt4 key购买 nike

我在将 objective-c 转换为 swift 时遇到问题。

对于我的火车,我转换了 MMPaper 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 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)
}
}

结果是(粗体问题):

libswiftCore.dylib`swift_dynamicCastClassUnconditional:
...
0x10cf7da1e: leaq 0x36b3d(%rip), %rax ; "Swift dynamic cast failed"
0x10cf7da25: movq %rax, 0xb4a2c(%rip) ; gCRAnnotations + 8
0x10cf7da2c: int3
**0x10cf7da2d: movq %rdi, %rax**
.....

你有想法吗?

最佳答案

通过使用 as 运算符,您是在告诉 Swift 您完全确定向下转换为 HomeViewController 会成功。但是,明明presentingVC.nextViewControllerAtPoint(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 看到 as?HomeViewController 时,它发现 presentingVC 的类型必须是 HomeViewController?。很抱歉,如果这很明显。)

关于xcode - self.navigationController.topViewController 作为 HomeViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26595698/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com