使用XIB实例化视图
我有一个由以下指南创建的xib( 如何创建自定义iOS视图类并实例化它的多个副本(在IB中)? )但我有一个问题:
如何从代码中实例化?
那么我应该在viewDidLoad中写什么而不是
self.myView = [[MyView alloc] initWithFrame:self.view.bounds];
我知道如何使用storyboard实例化它,但我不知道如何从代码中实现它。 谢谢!
您必须添加-loadNibNamed
方法,如下所示:
将以下代码添加到Your_View init
方法:
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"Your_nib_name" owner:self options:nil]; UIView *mainView = [subviewArray objectAtIndex:0]; [self addSubview:mainView];
在这里提到这两个问题:
将自定义子视图(在xib中创建)添加到视图控制器的视图中 – 我做错了什么
iOS:使用xib的自定义视图
编辑:
在您的ViewController.m
文件中
#import CustomView.h <--- //import your_customView.h file - (void)viewDidLoad { [super viewDidLoad]; CustomView *customView = [[CustomView alloc]init]; [self.view addSubview:customView]; }
这是我使用的Swift 4扩展:
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 } }
像这样用它:
override init(frame: CGRect) { super.init(frame: frame) initViewFromNib() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initViewFromNib() }