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.

Author: Garfbargle, 2015-05-19

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

  1. seleccione el xib
  2. seleccionar propietario del archivo
  3. establezca la clase personalizada en 'DesignableXibView' en el Inspector de Identidad.

Configurar el Propietario de un Xib a una clase personalizada

  • 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

  1. Abra su storyboard
  2. Añadir una vista
  3. Establecer la Clase Personalizada de esa vista
  4. espera un segundo ... BOOM!!

Representación Xib Dentro de un Controlador de Vista de Storyboard

 111
Author: Garfbargle,
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

  1. seleccione el xib
  2. seleccione el propietario del archivo
  3. Establezca la clase personalizada en 'ReusableView' en el Inspector de Identidad. introduzca la descripción de la imagen aquí

    • 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

  1. Editor Asistente abierto
  2. Control + Arrastre desde la vista a su interfaz

introduzca la descripción de la imagen aquí

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;
}

introduzca la descripción de la imagen aquí

Pruebe su vista reuseable en un storyboard

  1. Abra su storyboard
  2. Añadir una vista
  3. Establecer la Clase Personalizada de esa vista

introduzca la descripción de la imagen aquí

¡Corre y observa! introduzca la descripción de la imagen aquí

 69
Author: Garfbargle,
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

 44
Author: harsh_v,
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]))
    }
 11
Author: Ankit Goel,
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);
        }
    }
 0
Author: Yohan Dahmani,
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