我有一个XIB,是按照以下指南创建的(如何创建自定义iOS视图类并实例化多个副本(在IB中)?),但我有一个问题:
我该如何从代码中实例化它?
所以,在viewDidLoad中,我应该写什么而不是
self.myView = [[MyView alloc] initWithFrame:self.view.bounds];
我知道如何使用Storyboard实例化它,但是我不知道如何通过代码来做。谢谢!
我有一个XIB,是按照以下指南创建的(如何创建自定义iOS视图类并实例化多个副本(在IB中)?),但我有一个问题:
我该如何从代码中实例化它?
所以,在viewDidLoad中,我应该写什么而不是
self.myView = [[MyView alloc] initWithFrame:self.view.bounds];
我知道如何使用Storyboard实例化它,但是我不知道如何通过代码来做。谢谢!
init
方法中添加如下代码:-loadNibNamed
方法如下所示:NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"Your_nib_name" owner:self options:nil];
UIView *mainView = [subviewArray objectAtIndex:0];
[self addSubview:mainView];
#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
}
}
使用
let myView = MyView.makeFromNib()
let profileView = ProfileView.makeFromNib()
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()
}
[CustomView customView]
是什么? - user2786037customView
将是你的CustomView
类中的方法,其中你已经初始化了你的视图。即你已经加载了视图的 nib 文件。如果你是在-init
中编写代码,那么只需写[[CustomView alloc] init];
。 - Rumin