Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate view with XIB

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!

like image 708
user2786037 Avatar asked Mar 18 '23 03:03

user2786037


2 Answers

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];
}
like image 95
Cityzen26 Avatar answered Mar 28 '23 20:03

Cityzen26


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

like image 37
Alex Avatar answered Mar 28 '23 20:03

Alex