ios UIViewController 扩展不允许覆盖 Swift 中的视图相关功能?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29951979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
UIViewController extension not allowing to override view related functions in Swift?
提问by Hugo Alonso
While trying to implement an extension for UIViewControllerI realise that there is no normal way, or is not allowed to override this functions (even when they are available for UICollectionViewControllerand UITableViewController):
在尝试为UIViewController实现扩展时,我意识到没有正常的方法,或者不允许覆盖此功能(即使它们可用于UICollectionViewController和UITableViewController):
extension UIViewController{
public override func viewWillAppear(){
super.viewWillAppear()
//do some stuff
}
}
I realise that there is no normal way, or is not allowed to override this functions (even when they are available for UICollectionViewControllerand UITableViewController):
我意识到没有正常的方法,或者不允许覆盖这个函数(即使它们可用于UICollectionViewController和UITableViewController):
- viewDidLoad
- viewWillLoad
- viewWillAppear
- viewDidAppear
- 查看已加载
- 视图将加载
- 视图将出现
- 视图DidAppear
There is some way to do this? I would like to have some implementation there and working for every UIViewControlleron my app... All in just one place.
有没有办法做到这一点?我想在那里有一些实现,并为我的应用程序上的每个UIViewController工作......都在一个地方。
Please, note that I don'twant to make a new class subclassing UIViewController, overriding those methods and making my controller to extend it. This is the obvious and simplest solution, but this do not satisfy what I'm trying to do.
I'm using swift 1.2 in XCode 6.3
请注意,我不想创建一个子类化 UIViewController 的新类,覆盖这些方法并使我的控制器扩展它。这是最明显和最简单的解决方案,但这不能满足我想要做的。
我在 XCode 6.3 中使用 swift 1.2
回答by Antonio
What you are trying to do is similar to what done by this code:
您尝试执行的操作类似于此代码所做的操作:
class MyClass {
func myFunc() {}
}
extension MyClass {
override func myFunc() {}
}
The 4 methods that you are trying to override are defined in UIViewController
, and not to one of its superclasses. And you can't override a method which is defined in the same class.
您尝试覆盖的 4 个方法在 中定义UIViewController
,而不是在其超类之一中定义。并且您不能覆盖在同一类中定义的方法。
Update
更新
I can think of 2 different ways to solve the problem - the first is the one you don't want (subclassing UIViewController
).
我可以想到两种不同的方法来解决这个问题——第一种是你不想要的(子类化UIViewController
)。
The other one is method swizzling - I never used it so I don't want to provide you inaccurate info. Maybe it's worth reading this articleby Nate Cook, which incidentally is showing an example of replacing viewWillAppear
.
另一种是方法混合 - 我从未使用过它,所以我不想为您提供不准确的信息。也许值得一读Nate Cook 的这篇文章,它顺便展示了一个替换viewWillAppear
.