Swift中的自定义Segue [英] Custom Segue in Swift
问题描述
@objc(SEPushNoAnimationSegue)
class SEPushNoAnimationSegue: UIStoryboardSegue {
override func perform () {
self.sourceViewController.navigationController.pushViewController(self.destinationViewController, animated:false)
}
}
在上面的代码中,我有两个问题:
1)。它有一个编译错误:
'UINavigationController!'没有名为'pushViewController'的成员
In the above code, I have 2 questions: 1). it has a compile error: 'UINavigationController!' does not have a member named 'pushViewController'
但在该类中,它确实有一个pushViewController方法。
But in that class, it did has a pushViewController method.
2)。我必须添加注释:@objc(SEPushNoAnimationSegue),否则
,在storyboard中,它只识别随机生成的名称,如_tcxxxxSEPushNoAnimationSegue。
2). I have to add the annotation: @objc(SEPushNoAnimationSegue), otherwise, in storyboard, it only recognize the random generated name, like, _tcxxxxSEPushNoAnimationSegue.
为什么这两个问题发生在这里?
why these 2 issues happen here?
推荐答案
问题#1
UIStoryboardSegue有一个恼人的缺陷:它的sourceViewController和destinationViewController属性被输入为 AnyObject!
(即使在Objective-C(Id类型)中也是如此)而不是 UIViewController
,应该是。
Issue #1
UIStoryboardSegue has an irritating flaw: its sourceViewController and destinationViewController properties are typed as AnyObject!
(that's the case even in Objective-C (Id type)) and not as UIViewController
, as it should be.
同样的缺陷会在你完美而简单的代码中造成破坏。以下是如何重写它以修复编译错误:
That same flaw creates havoc in your perfect and simple code. Here's how to rewrite it in order to fix the compile errors:
@objc(SEPushNoAnimationSegue)
class SEPushNoAnimationSegue: UIStoryboardSegue {
override func perform () {
let src = self.sourceViewController as UIViewController
let dst = self.destinationViewController as UIViewController
src.navigationController.pushViewController(dst, animated:false)
}
}
注意:Apple在iOS 9中解决了这个问题。 sourceViewController
和 destinationViewController
现在已正确声明为 UIViewController
。
NOTE: Apple fixed this thing in iOS 9. sourceViewController
and destinationViewController
are now correctly declared as UIViewController
.
Swift编译器使用自己的名称错误,并且好的'Objective-C在Xcode中无法识别它。使用显式的 @obj()
解决了这个问题。
The Swift compiler stores its symbols using its own name mangling, and good ol' Objective-C does not recognize it in Xcode. Using an explicit @obj()
solves the issue.
这篇关于Swift中的自定义Segue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!