Talha Ch Talha Ch - 21 days ago 5
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

StoryboardID
as:

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


In
AddNewPatientViewController
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
init
it with this custom
init
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];

Answer

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:

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

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