Normalmente me gusta crear y diseñar mis vistas en el constructor de interfaces. A veces necesito crear una vista única en un xib que pueda reutilizarse en múltiples controladores de vista en un guión gráfico.
Probado con Swift 2.2 y Xcode 7.3.1
// 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 } }
¡NUEVO! respuesta actualizada con la capacidad de representar directamente en el guión gráfico (¡y rápido!)
Funciona en Xcode 6.3.1
Crea una nueva UIView llamada ‘ReuseableView’
Cree un archivo xib coincidente llamado ‘ReuseableView’
Establezca el propietario del archivo del xib
establece la clase personalizada como ‘Vista reutilizable’ en el Inspector de identidad.
Haga una salida desde la vista en ReuseableView.xib a su interfaz ReuseableView.h
Agregue la implementación de initWithCoder para cargar vista y agregar 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; }
Pon a prueba tu vista reutilizable en un guión gráfico
¡Corre y observa!
Swift 3 y 4 Actualización a la respuesta aceptada
1. Crea una nueva UIView llamada ‘DesignableXibView’
2. Cree un archivo xib coincidente llamado ‘DesignableXibView’
3. Establezca el propietario del archivo del xib
Seleccione “DesignableXibView.xib”> “Propietario del archivo”> configure “Clase personalizada” en “DesignableXibView” en el Inspector de identidad.
4. Implementación de XibView Designable
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 Pon a prueba tu vista reutilizable en un guión gráfico
Abra su guión gráfico
Añadir una vista
Establecer la clase personalizada de esa vista
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])) }