Talha Ch Talha Ch - 2 months ago 15
iOS Question

How to use custom init of ViewController in Storyboard

I have one storyboard in which all of my viewControllers are placed. I'm using


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

I've added a custom init method or constructor you can say as:

-(id) initWithoutAppointment
self = [super init];
if (self) {
self.roomBedNumberField.hidden = true;
return self;

So my question is by using the above wat of presenting view controller how can I
it with this custom
I've made.

I've tried doing this as areplacement of above code but it didn't work.

AddNewPatientViewController *viewController = [[AddNewPatientViewController alloc] initWithoutAppointment];
[self presentViewController:viewController animated:YES completion:nil];


You can't have a storyboard call a custom initializer.

You want to override init(coder:). That's the initializer that gets called when a view controller is created from a storyboard (or from a nib, for that matter.)

Your code might look something like this:


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

Note that in Swift your initializer must assign values to all non-optional properties before you call super.init, and that you must call super.init() (or in this case, super.init(coder:).