简体   繁体   English

如何在UIView中加载xib文件

[英]How to load a xib file in a UIView

I have been searching everywhere and nothing so far has worked for me. 我到处都在搜索,到目前为止没有什么对我有用。

Basically I want to have a .xib file called rootView.xib and inside it I want to have a UIView (lets call it containerView) that takes up only half of the screen (so there would be the regular view and a new view). 基本上我想要一个名为rootView.xib的.xib文件,在其中我希望有一个UIView(让我们称之为containerView)只占用屏幕的一半(因此会有常规视图和新视图)。 Then I want a different .xib file called firstView.xib and load it inside of containerView. 然后我想要一个名为firstView.xib的不同.xib文件并将其加载到containerView中。 So I can have a bunch of stuff on firstView.xib and a bunch of different stuff in rootView.xib and load my firstView.xib inside of containerView in rootView.xib but since it only takes up half of the screen you would still see the stuff on rootView.xib 所以我可以在firstView.xib上有一堆东西和rootView.xib中的一堆不同的东西,并在rootView.xib中加载我的firstView.xib在containerView内,但由于它只占用了屏幕的一半,你仍然可以看到rootView.xib上的东西

To get an object from a xib file programatically you can use: [[NSBundle mainBundle] loadNibNamed:@"MyXibName" owner:self options:nil] which returns an array of the top level objects in the xib. 要以编程方式从xib文件获取对象,可以使用: [[NSBundle mainBundle] loadNibNamed:@"MyXibName" owner:self options:nil] ,它返回xib中顶级对象的数组。

So, you could do something like this: 所以,你可以这样做:

UIView *rootView = [[[NSBundle mainBundle] loadNibNamed:@"MyRootView" owner:self options:nil] objectAtIndex:0];
UIView *containerView = [[[NSBundle mainBundle] loadNibNamed:@"MyContainerView" owner:self options:nil] lastObject];
[rootView addSubview:containerView];
[self.view addSubview:rootView];

I created a sample project on github to load a UIView from a .xib file inside another .xib file. 我在github上创建了一个示例项目,用于从另一个.xib文件中的.xib文件加载UIView。 Or you can do it programmatically. 或者你可以通过编程方式完成。

This is good for little widgets you want to reuse on different UIViewController objects. 这对于您希望在不同的UIViewController对象上重用的小部件非常有用。

  1. New Approach: https://github.com/PaulSolt/CustomUIView 新方法: https//github.com/PaulSolt/CustomUIView
  2. Original Approach: https://github.com/PaulSolt/CompositeXib 原始方法: https//github.com/PaulSolt/CompositeXib

从.xib文件加载自定义UIView

You could try: 你可以尝试:

UIView *firstViewUIView = [[[NSBundle mainBundle] loadNibNamed:@"firstView" owner:self options:nil] firstObject];
[self.view.containerView addSubview:firstViewUIView];

[Swift Implementation] [快速实施]

Universal way of loading view from xib: 从xib加载视图的通用方法:

Example: 例:

let myView = Bundle.loadView(fromNib: "MyView", withType: MyView.self)

Implementation: 执行:

extension Bundle {

    static func loadView<T>(fromNib name: String, withType type: T.Type) -> T {
        if let view = Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first as? T {
            return view
        }

        fatalError("Could not load view with type " + String(describing: type))
    }
}

Create a XIB file : 创建一个XIB文件:

File -> new File ->ios->cocoa touch class -> next 文件 - >新文件 - > ios-> cocoa touch class - > next

在此输入图像描述

make sure check mark "also create XIB file" 确保勾选“也创建XIB文件”

I would like to perform with tableview so I choosed subclass UITableViewCell 我想用tableview执行所以我选择了子类UITableViewCell

you can choose as your requerment 你可以选择作为你的申请

在此输入图像描述

XIB file desing as your wish (RestaurantTableViewCell.xib) XIB文件设计符合您的愿望(RestaurantTableViewCell.xib)

在此输入图像描述

we need to grab the row height to set table each row hegiht 我们需要抓住行高来设置每一行的表格

在此输入图像描述

Now! 现在! need to huck them swift file . 需要抓住他们快速文件。 i am hucked the restaurantPhoto and restaurantName you can huck all of you . 我很喜欢这里的restaurantPhotorestaurantName你可以帮到你们所有人。

在此输入图像描述

Now adding a UITableView 现在添加一个UITableView

在此输入图像描述

name 名称
The name of the nib file, which need not include the .nib extension. nib文件的名称,不需要包含.nib扩展名。

owner 所有者
The object to assign as the nib's File's Owner object. 要指定为nib的File的Owner对象的对象。

options 选项
A dictionary containing the options to use when opening the nib file. 包含打开nib文件时使用的选项的字典。

first if you do not define first then grabing all view .. so you need to grab one view inside that set frist . 第一 ,如果你不首先定义掠然后所有视图..所以,你需要抓住这组内的一个视图frist

Bundle.main.loadNibNamed("yourUIView", owner: self, options: nil)?.first as! yourUIView

here is table view controller Full code 这是表视图控制器的完整代码

import UIKit

class RestaurantTableViewController: UIViewController ,UITableViewDataSource,UITableViewDelegate{

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let restaurantTableviewCell = Bundle.main.loadNibNamed("RestaurantTableViewCell", owner: self, options: nil)?.first as! RestaurantTableViewCell

        restaurantTableviewCell.restaurantPhoto.image = UIImage(named: "image1")
        restaurantTableviewCell.restaurantName.text = "KFC Chicken"

        return restaurantTableviewCell
    }
   // set row height
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 150
    }

}

you done :) 你做完了:)

在此输入图像描述

对于快速3和4

let customView = Bundle.main.loadNibNamed("CustomView", owner: nil, options: nil)?.first as? CustomView

For Swift 4.2 对于Swift 4.2

Let's assume you have a class named NibView and associated nib file is NibView.xib 假设您有一个名为NibView的类,并且关联的nib文件是NibView.xib

class NibView: UIView {

    class func getScreen() -> NibView {
        let xib = Bundle.main.loadNibNamed(String(describing :self), owner: self, options: nil)
        let me = xib![0] as! NibView
        return me
    }

}

create an instance of the class and add in your view with your specific layout whatever you want 创建一个类的实例,并在您的视图中添加您想要的特定布局

let myView = NibView.getScreen()
self.yourView.addSubview(myView)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM