我有一个OC类UIViewController
,它声明了UIViewController
的一个类方法
+(BOOL)hasStoryBoard;
而且我还把这个类导入到xxx-Bridging-Header.h
文件中
我的swift类CustomVC
继承了UIViewController。我想覆盖 +(BOOL)hasStoryBoard
以提供一个 BOOL 类型的值。此方法将在其他类中调用以确定 CustomVC
的新实例的某些功能。
但是在我的 CustomVC.swift 中我找不到这样的方法:
覆盖类 func hasStoryBoard()->bool{}
我必须覆盖此方法以提供YES
,或为其子类提供NO
,依此类推...
我搜索了这个网站并找到了这个 Swift: How to call a category or class method from Objective-C .在此讨论中,解释并告诉您如何调用该方法,而不是如何覆盖该方法。
您能找到覆盖 oc 类别的类方法的解决方案吗? 或者针对我的情况提供解决方法。
我所有的代码是:
@interface UIViewController (StoryBoard)
+(BOOL)hasStoryBoard;
-(void)haha;
@end
.
@implementation UIViewController (StoryBoard)
static BOOL hasStoryboard = NO;//默认没有
+(BOOL)hasStoryBoard{
return hasStoryboard;
}
-(void)haha{}
@end
.
class CustomVC: UIViewController {
//this override is correct,have syntax input prompt
override func haha() {
}
//this override is incorrect ,no syntax input prompt
override func hasStoryBoard()->Bool{
return true
}
}
最佳答案
+(BOOL)hasStoryBoard;
在 Objective-C 中定义了一个 class 方法,但是在你的 Swift 子类中 您定义一个实例方法:
override func hasStoryBoard()->Bool{
return true
}
那也必须是一个类方法:
override class func hasStoryBoard()->Bool{
return true
}
提示:如果您在 Xcode 中打开 Objective-C 接口(interface) (.h) 文件并 从 Xcode 菜单中选择“Navigate->Jump to Generated Interface” 然后你会清楚地看到 Objective-C 接口(interface)是如何导入到 swift 。在你的情况下:
extension UIViewController {
open class func hasStoryBoard() -> Bool
open func haha()
}
现在您可以复制函数定义并使用它来定义 子类中的重写方法。
关于ios - 如何覆盖 .swift 中的 oc 类别方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42736049/