如何在 Storyboard 中使用 ViewController 的自定义初始化

How to use custom init of ViewController in Storyboard

我有一个故事板,其中放置了我所有的 viewController。我正在使用 StoryboardID 作为:

AddNewPatientViewController * viewController =[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"addNewPatientVC"];
 [self presentViewController:viewController animated:YES completion:nil];

AddNewPatientViewController 中,我添加了一个自定义初始化方法或构造函数,您可以这样说:

-(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;
}

但这不是一个好的代码

已编辑

可能是样式问题,但我宁愿不这样做,因为视图控制器不必了解 UIStoryboard;如果你想有这样的方法,最好把它移到一些单独的工厂。 如果我选择在没有 Storyboard 的其他项目中使用此 VC,或者使用 Storyboard,但使用另一个名称,它将容易出错。

您不能让故事板调用自定义初始化程序。

您想覆盖 init(coder:)。这是从情节提要(或从 nib,就此而言)创建视图控制器时调用的初始化程序。

您的代码可能如下所示:

Objective-C:

- (instancetype)initWithCoder:(NSCoder *)aDecoder; {
    [super initWithCoder: aDecoder];
    //your init code goes here.
}

Swift:

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:)