'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]; 


Solution 1:[1]

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

Solution 2:[2]

Add this in your kotlin class file, where you want to inflate the layout.

import kotlinx.android.synthetic.main.activity_main.*

And in the build.gradle (:app) file add as below in plugins

id 'kotlin-android'
id 'kotlin-android-extensions'

Note : Use the element id, not the file itself

<androidx.appcompat.widget.AppCompatTextView
    android:id="@+id/list_item"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Zaid Reshamwale