Ios 用XIB实例化视图

Ios 用XIB实例化视图,ios,objective-c,Ios,Objective C,我有一个按照以下指南()创建的xib,但我有一个问题: 如何从代码实例化if 那么我应该在viewDidLoad中写什么而不是 self.myView = [[MyView alloc] initWithFrame:self.view.bounds]; 我知道如何用故事板来实例化它,但我不知道如何从代码中实现它。谢谢 您必须添加-loadNibNamed方法,如下所示: 将以下代码添加到\u视图init方法中: NSArray *subviewArray = [[NSBundle mainBu

我有一个按照以下指南()创建的xib,但我有一个问题:

如何从代码实例化if

那么我应该在viewDidLoad中写什么而不是

self.myView = [[MyView alloc] initWithFrame:self.view.bounds];

我知道如何用故事板来实例化它,但我不知道如何从代码中实现它。谢谢

您必须添加
-loadNibNamed
方法,如下所示:

将以下代码添加到\u视图
init
方法中:

NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"Your_nib_name" owner:self options:nil];
UIView *mainView = [subviewArray objectAtIndex:0];
[self addSubview:mainView];
请参考以下两个问题:

编辑:

ViewController.m
文件中

#import CustomView.h   <--- //import your_customView.h file

- (void)viewDidLoad
{
    [super viewDidLoad];

    CustomView *customView = [[CustomView alloc]init];
    [self.view addSubview:customView];
}

#import CustomView.h以下是我使用的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()
}
斯威夫特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()
    }
}

是的,很清楚。但是我应该在ViewController中做什么才能从nib添加视图?什么是
[CustomView CustomView]
CustomView
将是您初始化视图的
CustomView
类的方法。i、 在其中加载了视图的nib文件。如果您是在
-init
中编写代码,那么只需编写
[[CustomView alloc]init]
let myView = MyView.makeFromNib()
let profileView = ProfileView.makeFromNib()