ios 如何在 UIView 中加载 xib 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7814928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:56:02  来源:igfitidea点击:

How to load a xib file in a UIView

iosobjective-cuiviewxib

提问by Matt

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). Then I want a different .xib file called firstView.xib and load it inside of 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

基本上我想要一个名为 rootView.xib 的 .xib 文件,在里面我想要一个 UIView(我们称之为 containerView),它只占屏幕的一半(所以会有常规视图和新视图)。然后我想要一个名为 firstView.xib 的不同 .xib 文件并将其加载到 containerView 中。所以我可以在 firstView.xib 上有一堆东西,在 rootView.xib 中有一堆不同的东西,并在 rootView.xib 的 containerView 中加载我的 firstView.xib 但因为它只占屏幕的一半,你仍然会看到rootView.xib 上的东西

回答by chown

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

回答by Paul Solt

I created a sample project on github to load a UIView from a .xib file inside another .xib file. Or you can do it programmatically.

我在 github 上创建了一个示例项目,用于从另一个 .xib 文件中的 .xib 文件加载 UIView。或者您可以以编程方式执行此操作。

This is good for little widgets you want to reuse on different UIViewController objects.

这对于您想在不同 UIViewController 对象上重用的小部件很有用。

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

Load a Custom UIView from .xib file

从 .xib 文件加载自定义 UIView

回答by NJones

You could try:

你可以试试:

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

回答by Максим Мартынов

[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))
    }
}

回答by Nazmul Hasan

Create a XIB file :

创建一个 XIB 文件:

File -> new File ->ios->cocoa touch class -> next

File -> new File ->ios->cocoa touch class -> next

enter image description here

在此处输入图片说明

make sure check mark "also create XIB file"

确保选中“同时创建 XIB 文件”

I would like to perform with tableviewso I choosed subclass UITableViewCell

我想表演tableview所以我选择了子类UITableViewCell

you can choose as your requerment

您可以选择作为您的要求

enter image description here

在此处输入图片说明

XIB file desing as your wish (RestaurantTableViewCell.xib)

随心所欲设计的 XIB 文件 (RestaurantTableViewCell.xib)

enter image description here

在此处输入图片说明

we need to grab the row height to set table each row hegiht

我们需要获取行高来设置表格每一行的高度

enter image description here

在此处输入图片说明

Now! need to huck them swift file . i am hucked the restaurantPhotoand restaurantNameyou can huck all of you .

现在!需要破解他们的 swift 文件。我被砍了restaurantPhotorestaurantName你可以砍掉你们所有人。

enter image description here

在此处输入图片说明

Now adding a UITableView

现在添加一个 UITableView

enter image description here

在此处输入图片说明

name
The name of the nib file, which need not include the .nib extension.

name
nib 文件的名称,不需要包含 .nib 扩展名。

owner
The object to assign as the nib's File's Owner object.

owner
要分配为笔尖的 File's Owner 对象的对象。

options
A dictionary containing the options to use when opening the nib file.

options
包含打开 nib 文件时使用的选项的字典。

firstif 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 :)

你完成了:)

enter image description here

在此处输入图片说明

回答by raed

For swift 3 & 4

快速 3 & 4

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

回答by Noshaid Ali

For Swift 4.2

对于Swift 4.2

Let's assume you have a class named NibViewand associated nib file is NibView.xib

假设您有一个名为NibView的类,关联的笔尖文件是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)