Reutilice un uiview xib en storyboard
Normalmente me gusta crear y diseñar mis uiviews en interface builder. A veces necesito crear una sola vista en un xib que se pueda reutilizar en varios controladores de vista en un guion gráfico.
5 answers
Reutilice y renderice un xib en un guion gráfico.
Probado con Swift 2.2 & Xcode 7.3.1
1 ---- Crear una nueva UIView llamada'DesignableXibView'
- Archivo > Nuevo > Archivo > Fuente > Clase Cocoa Touch > UIView
2 ---- Crear un archivo xib coincidente llamado'DesignableXibView'
- Archivo > Nuevo > Archivo > Interfaz de usuario > Ver
3 ---- Establecer el propietario del archivo de la xib
- seleccione el xib
- seleccionar propietario del archivo
- establezca la clase personalizada en 'DesignableXibView' en el Inspector de Identidad.
- Nota: No establezca la clase personalizada de la vista en el xib. Sólo el Propietario del Archivo!
4 ---- Implementación de DesignableXibView
// DesignableXibView.swift
import UIKit
@IBDesignable
class DesignableXibView: UIView {
var contentView : UIView?
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
contentView = loadViewFromNib()
// use bounds not frame or it'll be offset
contentView!.frame = bounds
// Make the view stretch with containing view
contentView!.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(contentView!)
}
func loadViewFromNib() -> UIView! {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: String(self.dynamicType), bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
}
5 ---- Pruebe su vista reuseable en un storyboard
- Abra su storyboard
- Añadir una vista
- Establecer la Clase Personalizada de esa vista
- espera un segundo ... BOOM!!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-07 00:38:21
¡NUEVO! respuesta actualizada con capacidad de renderizar directamente en el storyboard (y swift!)
Funciona en Xcode 6.3.1
Crear una nueva UIView llamada 'ReuseableView'
- Archivo > Nuevo > Archivo > Fuente > Clase Cocoa Touch > UIView
Crear un archivo xib coincidente llamado 'ReuseableView'
- Archivo > Nuevo > Archivo > Interfaz de usuario > Ver
Establecer el propietario del archivo de la de xib
- seleccione el xib
- seleccione el propietario del archivo
-
Establezca la clase personalizada en 'ReusableView' en el Inspector de Identidad.
- Nota: No establezca la clase personalizada de la vista en el xib. Sólo el Propietario del Archivo!
Hacer una salida de la vista en el ReuseableView.xib a su ReuseableView.interfaz h
- Editor Asistente abierto
- Control + Arrastre desde la vista a su interfaz
Agregue la implementación de initWithCoder para cargar la vista y agregue como una subvista.
- (id)initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if (self) {
// 1. load the interface
[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil];
// 2. add as subview
[self addSubview:self.view];
// 3. allow for autolayout
self.view.translatesAutoresizingMaskIntoConstraints = NO;
// 4. add constraints to span entire view
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view]|" options:0 metrics:nil views:@{@"view":self.view}]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|" options:0 metrics:nil views:@{@"view":self.view}]];
}
return self;
}
Pruebe su vista reuseable en un storyboard
- Abra su storyboard
- Añadir una vista
- Establecer la Clase Personalizada de esa vista
¡Corre y observa!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:26
Swift 3 & 4 Actualización de la respuesta aceptada
1. Crear una nueva UIView llamada'DesignableXibView'
- Archivo > Nuevo > Archivo > Fuente > Clase Cocoa Touch > UIView
2. Crear un archivo xib coincidente llamado'DesignableXibView'
- Archivo > Nuevo > Archivo > Interfaz de usuario > Ver
3. Establecer el propietario del archivo de la xib
Seleccione "DesignableXibView.xib " > "Propietario del archivo" > establecer " Personalizado Class " a 'DesignableXibView' en el Inspector de Identidad.
- Nota: No establezca la clase personalizada de la vista en el xib. Sólo el ¡Dueño del archivo!
4. Implementación de DesignableXibView
import UIKit
@IBDesignable
class DesignableXibView: UIView {
var contentView : UIView!
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
contentView = loadViewFromNib()
// use bounds not frame or it'll be offset
contentView.frame = bounds
// Make the view stretch with containing view
contentView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(contentView)
}
func loadViewFromNib() -> UIView! {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
return view
}
}
5 Pruebe su vista reutilizable en un storyboard
-
Abra su storyboard
-
Añadir una vista
-
Establecer la Clase Personalizada de esa vista
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-31 06:54:19
La función initWithCoder en swift 2 si alguien tiene problemas para traducirla:
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
UINib(nibName: String(self.dynamicType), bundle: NSBundle.mainBundle()).instantiateWithOwner(self, options: nil)
self.addSubview(view)
self.view.translatesAutoresizingMaskIntoConstraints = false
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options: NSLayoutFormatOptions.AlignAllCenterY , metrics: nil, views: ["view": self.view]))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: NSLayoutFormatOptions.AlignAllCenterX , metrics: nil, views: ["view": self.view]))
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-30 00:29:31
Si alguien está interesado, aquí está el Xamarin.iOS versión del código Paso 4 de @Garfbargle
public partial class CustomView : UIView
{
public ErrorView(IntPtr handle) : base(handle)
{
}
[Export("awakeFromNib")]
public override void AwakeFromNib()
{
var nibObjects = NSBundle.MainBundle.LoadNib("CustomView", this, null);
var view = (UIView)Runtime.GetNSObject(nibObjects.ValueAt(0));
view.Frame = Bounds;
view.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
AddSubview(rootView);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-26 14:56:54