Search code examples
iosuisegmentedcontrol

Swift: Programmatically changing my UISegmentedControl's Items


I want to change the items in my UISegmentedControl based off of another selection. I do not want to change the number of items, but simply the item labels, as well as the 'hidden' variable of the UISegmentedControl.

Here is my code to get the UISegmentedControl:

@IBOutlet weak var viewPicker: UISegmentedControl!

and here is the code to change it:

viewPicker = UISegmentedControl(items: ["Description", "Location"])

However, this doesn't work and sometimes sets viewPicker to nil, giving an error. What is the best way to do this?


Solution

  • Since you are declaring your variable as "weak", it will get deallocated as soon as you assign it. But you should not do it anyway, because it is @IBOutlet -> you should connect it through interface builder.

    As for changing the title, instead of just creating new SC, use

    self.viewPicker.setTitle("", forSegmentAtIndex: index)
    

    And to hide / show segmented control,

    self.viewPicker.hidden = true / false
    

    Hope it helps!