2
我有一个Objective-C初始值设定项(来自另一个项目),我发现它很有用。现在我想将它移植到Swift中,并且Swift的命名约定存在问题。重写Objective-C无参数初始化为Swift方便初始化
.H
@interface UIViewController (FromNib)
-(nullable instancetype)initFromNib;
@end
的.m
#import "FromNib.h"
@implementation UIViewController (FromNib)
-(nullable instancetype)initFromNib {
self = [self initWithNibName: NSStringFromClass([self class])
bundle: [NSBundle mainBundle]];
if (self == nil) {
NSLog(@"\nNib with name %@ not found in the main bundle.\n", NSStringFromClass([self class]));
}
return self;
}
@end
由于Objective-C的识别方法,其名称与init
开始它把从init
或initWith...
作为initFrom
不同。 Swift根据传递的参数进行区分。只有这样,(我认为),使init()
不同于我的初始化是通过伪参数:
extension UIViewController {
convenience init(FromNib:Int) {
self.init()
// the rest of the code
}
}
有没有写在斯威夫特一个无参数的init不同的方式,并避免它被混同指定init()
?
不是默认的'UIViewController.init'和你的'initWithNib'完全一样吗?无论如何,唯一的解决方法是使用“类方法”,例如'class func createFromNib(){...}'。 – Sulthan
请注意,虚拟参数*可以是void:'便捷init(fromNib:Void)',然后将其称为'let vc = ViewController(fromNib:())'。 –
但是@Sulthan是正确的:'let vc = MyViewController()'从主包中的“MyViewController.nib”自动加载视图控制器。 –