1

I'm trying to do a simple control to simulate "android tabs" that I can use in xcode interface designer.

So I made a simple XIB which has few interface objects (scroll, stack, uiview...) and gave him a class called "TabsCustomControl"

my problem now is to know how I should do the setup/initialize this xib/UIView class.

In my mind it makes sense that you pass parameters to the xib/custom UIView when its initialized so it knows what sizes/colors/images the tabs should have based on the count of tabs.

But as soon I run

let tabsCustomControl = Bundle.main.loadNibNamed("TabsCustomControl", owner: self, options: nil)!.first as! TabsCustomControl

I dont have a chance to config it

tabsCustomControl.tabs = ["first tab"]

it runs the init... but I still haven't defined the property with tab list [String] so now what happens is that the code is run without any information regarding the tabs.

@IBInspectable var tabs : [String] = []

override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
}

private func setup()
{       
     // THIS IS Empty, so loop is not running
    for _ in tabs {

        let newTab = UIButton()
        newTab.backgroundColor = UIColor.green
        newTab.setTitle("Test", for: .normal)

        horizontalStackView.addArrangedSubview(newTab)
    }
}

I can fix this by running setup() function after the class is initialized and parameters set, but this seems bad since i will use it in many places... i will be stuck with calling the .setup() each time after I create the xib

what approach should i be using?

  • Yeah, there isn't much you can do around this other than to create the nib/view controller and then set properties on it. If it gets to the point where you NEED to set properties in the init method then you could always move away from nibs and create it in code. Or something? – Fogmeister Aug 01 '18 at 11:55
  • *"I can use in xcode interface designer"* ... Do you mean you want to use `@IBDesignable` so you can see the "tabs" during layout in storyboard? – DonMag Aug 01 '18 at 12:00
  • @DonMag yes thats the idea – João Serra Aug 01 '18 at 12:32
  • @JoãoSerra - OK, take a look at this answer... should be pretty much what you're going for: https://stackoverflow.com/a/43078869/6257435 – DonMag Aug 01 '18 at 12:40

1 Answers1

1

Maybe run setup in the didSet

@IBInspectable var tabs : [String] = [] {
    didSet {
        setup()
    }

This will mean you will have to ensure that you do set the tabs after you init the VC

Funi1234
  • 35
  • 1
  • 8