Reputation: 505
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!
Upvotes: 4
Views: 4882
Reputation: 1601
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()
Upvotes: 2
Reputation: 6418
Here is a Swift 4 extension that I use:
public extension UIView {
// Load the view for this class from a XIB file
public func viewFromNibForClass(index : Int = 0) -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
return nib.instantiate(withOwner: self, options: nil)[index] as! UIView
}
// Load the view for this class from a XIB file and add it
public func initViewFromNib() {
let view = viewFromNibForClass()
addSubview(view)
//view.frame = bounds // No Autolayout
view.constrainToFillSuperview() // Autolayout helper
}
}
Use it like this:
override init(frame: CGRect) {
super.init(frame: frame)
initViewFromNib()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initViewFromNib()
}
Upvotes: 0
Reputation: 3790
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
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];
}
Upvotes: 6