使用XIB实例化视图

时间:2014-10-22 04:05:05

标签: ios objective-c

我有一个按照指南(How do I create a custom iOS view class and instantiate multiple copies of it (in IB)?)创建的xib,但我有一个问题:

如何从代码中实例化?

那么我应该在viewDidLoad而不是

中写什么
self.myView = [[MyView alloc] initWithFrame:self.view.bounds];

我知道如何使用storyboard实例化它,但我不知道如何从代码中实现它。谢谢!

3 个答案:

答案 0 :(得分:4)

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

将以下代码添加到Your_View init方法:

NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"Your_nib_name" owner:self options:nil];
UIView *mainView = [subviewArray objectAtIndex:0];
[self addSubview:mainView];

在这里提到这两个问题:

Adding a custom subview (created in a xib) to a view controller's view - What am I doing wrong

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];
}

答案 1 :(得分:1)

雨燕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()
    }
}

使用

let myView = MyView.makeFromNib()
let profileView = ProfileView.makeFromNib()

答案 2 :(得分: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()
}