4

Is it possible to create reusable stack views on the story board that can be used dynamically to be generated at a later time? Sort of a template/widget/component.

I am aware that I can do this with a class but if I am able to visually generate a set of components that can be re-used at a latter time I may be able to let our designers make changes to storyboards directly.

Helmut Granda
  • 4,565
  • 7
  • 35
  • 51

2 Answers2

3

Yes -- you can do this with any UIView. There are many tutorials for this (e.g. http://onedayitwillmake.com/blog/2013/07/ios-creating-reusable-uiviews-with-storyboard/)

The basic idea is to drag one onto Storyboard or XIB, make a custom class for it, then implement the view's awakeFromNib to load it.

Lou Franco
  • 87,846
  • 14
  • 132
  • 192
3

Yes.It is.

  1. Create a empty xib and then add a stack view to it.
  2. Then create a class which extends UIStackView.

    class stackView: UIStackView {
    
    var contentView : UIStackView!
    override init(frame: CGRect) {
        super.init(frame: frame)
        xibSetup()
    }
    
    required init(coder: NSCoder) {
        super.init(coder: coder)
        xibSetup()    }
    
    func xibSetup() {
        contentView = loadViewFromNib() 
        contentView.frame = bounds
        contentView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
        addSubview(contentView)
    }
    
    func loadViewFromNib() -> UIStackView! {
    
        let view: UIStackView? = Bundle.main.loadNibNamed("stackView", owner: nil, options: nil)?.first as! UIStackView?
        return view
    }
    
  3. Create a viewController.Add a stackView to it.In StackView properties, goto 3rd bar which named as custom class, for class name give stackView class name

ireshika piyumalie
  • 2,226
  • 22
  • 22