使用XIB实例化视图

4

我有一个XIB,是按照以下指南创建的(如何创建自定义iOS视图类并实例化多个副本(在IB中)?),但我有一个问题:

我该如何从代码中实例化它?

所以,在viewDidLoad中,我应该写什么而不是

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

我知道如何使用Storyboard实例化它,但是我不知道如何通过代码来做。谢谢!

3个回答

6
你需要在 Your_View 的 init 方法中添加如下代码:-loadNibNamed 方法如下所示:
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"Your_nib_name" owner:self options:nil];
UIView *mainView = [subviewArray objectAtIndex:0];
[self addSubview:mainView];

请参考以下两个问题:
- 将自定义子视图(在xib中创建)添加到视图控制器的视图中 - 我做错了什么:Adding a custom subview (created in a xib) to a view controller's view - What am I doing wrong - iOS:带有xib的自定义视图:iOS: Custom view with xib 编辑:
在您的ViewController.m文件中。
#import CustomView.h   <--- //import your_customView.h file

- (void)viewDidLoad
{
    [super viewDidLoad];

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

是的,这很清楚。但我应该在ViewController中做什么来从nib添加视图? - user2786037
[CustomView customView]是什么? - user2786037
customView 将是你的 CustomView 类中的方法,其中你已经初始化了你的视图。即你已经加载了视图的 nib 文件。如果你是在 -init 中编写代码,那么只需写[[CustomView alloc] init]; - Rumin

2

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()


0
这是我使用的一个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()
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接