[英]How to use custom init of ViewController in Storyboard
我有一个故事板,其中放置了所有的viewControllers。 我正在使用StoryboardID
:
AddNewPatientViewController * viewController =[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"addNewPatientVC"];
[self presentViewController:viewController animated:YES completion:nil];
在AddNewPatientViewController
我添加了一个自定义的init方法或构造函数,你可以这样说:
-(id) initWithoutAppointment
{
self = [super init];
if (self) {
self.roomBedNumberField.hidden = true;
}
return self;
}
所以我的问题是通过使用上面提到的视图控制器的wat,我如何使用我已经制作的这个自定义init
来init
它。
我已尝试将此作为上述代码的替换,但它不起作用。
AddNewPatientViewController *viewController = [[AddNewPatientViewController alloc] initWithoutAppointment];
[self presentViewController:viewController animated:YES completion:nil];
使用这种方法不是最好的主意。 首先,我建议你在实例化后设置这个属性; 会更好
如果你想要制作这样的构造函数,你可以将代码放在实例化中,所以看起来就像
-(id) initWithoutAppointment
{
self = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"addNewPatientVC"];
if (self) {
self.roomBedNumberField.hidden = true;
}
return self;
}
但它不是一个好的代码
EDITED
可能是风格问题,但我宁愿不这样做,因为视图控制器不必知道UIStoryboard; 如果你想拥有这样的方法,最好把它移到一个单独的工厂。 如果我选择在没有Storyboard或故事板的其他项目中使用此VC,但使用其他名称,则会容易出错。
您不能让故事板调用自定义初始化程序。
你想要覆盖init(coder:)
。 这是从故事板(或从笔尖创建视图控制器)时调用的初始化程序。
您的代码可能如下所示:
- (instancetype)initWithCoder:(NSCoder *)aDecoder; {
[super initWithCoder: aDecoder];
//your init code goes here.
}
required init?(coder: NSCoder) {
//Your custom initialization code goes here.
print("In \(#function)")
aStringProperty = "A value"
super.init(coder: coder)
}
请注意,在Swift中,初始化程序必须在调用super.init之前为所有非可选属性赋值,并且必须调用super.init()
(或者在本例中为super.init(coder:)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.