Cha*_*lha 3 constructor objective-c init ios uistoryboard
我有一个故事板,其中放置了所有的viewControllers.我用的StoryboardID是:
AddNewPatientViewController * viewController =[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"addNewPatientVC"];
[self presentViewController:viewController animated:YES completion:nil];
Run Code Online (Sandbox Code Playgroud)
在AddNewPatientViewController我添加了一个自定义的init方法或构造函数,你可以说:
-(id) initWithoutAppointment
{
self = [super init];
if (self) {
self.roomBedNumberField.hidden = true;
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是通过使用上面提到的视图控制器的视图,我怎么能用我init做的这个定制init.
我已尝试将此作为上述代码的替换,但它不起作用.
AddNewPatientViewController *viewController = [[AddNewPatientViewController alloc] initWithoutAppointment];
[self presentViewController:viewController animated:YES completion:nil];
Run Code Online (Sandbox Code Playgroud)
使用这种方法不是最好的主意。首先,我建议您在实例化后设置此属性。会更好
无论如何,如果您想创建这样的构造函数,则可以将其带有实例化的代码放入其中,因此它看起来像
-(id) initWithoutAppointment
{
self = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"addNewPatientVC"];
if (self) {
self.roomBedNumberField.hidden = true;
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
但这不是一个好的代码
已编辑
可能是样式问题,但我宁愿不要这样做,因为视图控制器不必了解UIStoryboard。如果您想使用这种方法,最好将其移至其他工厂。如果我选择在没有Storyboard或带Storyboard的其他项目中使用此VC,但使用其他名称,它将很容易出错。
您不能让故事板调用自定义初始化程序.
你想要覆盖init(coder:).这是从故事板(或从笔尖创建视图控制器)时调用的初始化程序.
您的代码可能如下所示:
- (instancetype)initWithCoder:(NSCoder *)aDecoder; {
[super initWithCoder: aDecoder];
//your init code goes here.
}
Run Code Online (Sandbox Code Playgroud)
required init?(coder: NSCoder) {
//Your custom initialization code goes here.
print("In \(#function)")
aStringProperty = "A value"
super.init(coder: coder)
}
Run Code Online (Sandbox Code Playgroud)
请注意,在Swift中,初始化程序必须在调用super.init之前为所有非可选属性赋值,并且必须调用super.init()(或者在这种情况下,super.init(coder:).