[英]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.