I have a xib created by following guide (How do I create a custom iOS view class and instantiate multiple copies of it (in IB)?) but I have a question:
how can I instantiate if from code?
So what should I write in viewDidLoad instead of
self.myView = [[MyView alloc] initWithFrame:self.view.bounds];
I know how to instantiate it with storyboard, but I have no idea how to do it from code. Thanks!
You will have to add -loadNibNamed
method like following:
Add the following code to your Your_View init
method:
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"Your_nib_name" owner:self options:nil];
UIView *mainView = [subviewArray objectAtIndex:0];
[self addSubview:mainView];
Refer these two questions here:
Adding a custom subview (created in a xib) to a view controller's view - What am I doing wrong
iOS: Custom view with xib
EDIT:
In your ViewController.m
file
#import CustomView.h <--- //import your_customView.h file
- (void)viewDidLoad
{
[super viewDidLoad];
CustomView *customView = [[CustomView alloc]init];
[self.view addSubview:customView];
}
Swift 4
extension UIView {
class func makeFromNib() -> Self {
let nibName = String(describing: self)
let bundle = Bundle(for: self)
let nib = UINib(nibName: nibName, bundle: bundle)
let view = nib.instantiate(withOwner: nil, options: nil)[0]
return view as! Self
}
}
use
let myView = MyView.makeFromNib()
let profileView = ProfileView.makeFromNib()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With