2011-10-18 30 views
91

He estado buscando en todas partes y hasta ahora nada me ha funcionado.Cómo cargar un archivo xib en un UIView

Básicamente quiero tener un archivo .xib llamado rootView.xib y dentro de él quiero tener un UIView (vamos a llamarlo containerView) que ocupa solo la mitad de la pantalla (por lo que no sería la vista normal y una nueva vista). Luego quiero un archivo .xib diferente llamado firstView.xib y cargarlo dentro de containerView. Así que puedo tener un montón de cosas en FirstView.xib y un montón de cosas diferentes en rootView.xib y cargar mi primerView.xib dentro de containerView en rootView.xib pero dado que solo ocupa la mitad de la pantalla, aún verías el cosas en rootView.xib

+2

Nota, este questin es arcaico. Durante muchos años, simplemente use vistas de contenedor [tutorial] (http://stackoverflow.com/questions/23399061/objective-c-how-to-add-a-subview-that-has-its-own-uiviewcontroller/23403979 # 23403979) – Fattie

Respuesta

162

Para obtener un objeto de un archivo xib programáticamente puede usar: [[NSBundle mainBundle] loadNibNamed:@"MyXibName" owner:self options:nil] que devuelve una matriz de los objetos de nivel superior en el xib.

lo tanto, usted podría hacer algo como esto:

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]; 
+1

@Matt Pagar mi solución en github. https://github.com/PaulSolt/CompositeXib –

+0

@PaulSolt señor, tengo una consulta relacionada con este queston. Quiero abrir una subvista de xib como menú de diapositivas. Cuando hago clic en el botón de menú desde el controlador de vista, solo la vista secundaria (que es la mitad de la pantalla de xib) debe ser deslizante. por favor ayuda si es posible. –

+0

No funciona con 'thisView.alpha = 0',' thisView.superview' (muestra nada) – Jack

13

usted podría intentar:

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

No es precisamente lo que sugirió. Dijo que su "rootView.xib" tendría una subvista de la mitad del tamaño de la pantalla llamada "containerView". Y en containerView quería cargar el contenido de su plumín "firstView.xib". – NJones

7

[La aplicación Swift]

forma universal de vista de carga de xib:

Ejemplo:

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

Implementación:

extension NSBundle { 

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

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

Crear un archivo XI ter:

Archivo -> Nuevo Archivo -> ios-> cacao clase táctil -> siguiente

enter image description here

crea marca de verificación seguro "también crean archivos XI ter"

me gustaría realizar con tableview así que choosed subclase UITableViewCell

se puede elegir como su requerment

enter image description here

archivo XI ter diseño como desee (RestaurantTableViewCell.xib)

enter image description here

tenemos que agarrar el alto de fila para establecer la mesa cada fila hegiht

enter image description here

Ahora! Necesito darles un rápido archivo. Me dieron mala suerte el restaurantPhoto y el restaurantName que les puedo dar a todos.

enter image description here

Ahora la adición de un UITableView

enter image description here

nombre
El nombre del archivo de la semilla, que no necesita incluir la extensión .nib.

propietario
El objeto asignar como objeto del propietario del archivo de la punta.

opciones
un diccionario que contiene las opciones para utilizar al abrir el archivo de la plumilla.

primera si no se define primero y luego grabing todo punto de vista .. Así que hay que agarrar una vista interior de ese conjunto frist.

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

aquí es mesa de controlador de vista de código completo

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 
    } 

} 

has hecho :)

enter image description here

+0

podría decirme por favor. ¿Por qué votar abajo? Me alegrará –

+4

Su ejemplo está bien para verlo desde la carga xib. Pero para tableView está mal: las células reutilizables son la forma correcta – Viktor

Cuestiones relacionadas