Create view using XIB
I have a xib created with the following tutorial ( How to create a custom iOS view class and create multiple instances 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 create an instance using storyboard, but I have no idea how to do it from code. Thank!
source to share
You need to add a method -loadNibNamed
like below:
Add the following code to your Your_View method init
:
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"Your_nib_name" owner:self options:nil];
UIView *mainView = [subviewArray objectAtIndex:0];
[self addSubview:mainView];
Please refer to these two questions here:
Adding a custom subview (created in xib) to the view of the view controller - 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];
}
source to share
Here's the Swift 4 extension I'm using:
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()
}
source to share
Swift 4
extension UIView {
private class func _makeFromNib<T: UIView>() -> T {
let nibName = NSStringFromClass(T.self).components(separatedBy: ".").last ?? ""
let bundle = Bundle(for: T.self)
let nib = UINib(nibName: nibName, bundle: bundle)
let view = nib.instantiate(withOwner: T.self, options: nil)[0]
return view as! T
}
class func makeFromNib() -> Self {
return _makeFromNib()
}
}
use
let myView = MyView.makeFromNib()
let profileView = ProfileView.makeFromNib()
source to share