Swift: changing UISegmentedControl elements programmatically

I want to change the items in my UISegmentedControl based on a different selection. I don't want to change the number of items, but just the item labels as well as the "hidden" variable UISegmentedControl.

Here is my code for getting the UISegmentedControl:

@IBOutlet weak var viewPicker: UISegmentedControl!

      

and here is the code to change it:

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

      

However, this does not work and sometimes setPicker sets to nil, giving an error. What's the best way to do this?

+3


source to share


3 answers


Since you are declaring your variable as "weak", it will be deallocated as soon as you assign it. But you shouldn't do that anyway, because it's @IBOutlet -> you should hook it up via the interface constructor.

As for changing the title, not just creating a new SC, use

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

      



And to hide / show the segmented control,

self.viewPicker.hidden = true / false

      

Hope it helps!

+4


source


In UISegmentControl there is a method to change the labels individually named: setTitle(_:forSegmentAtIndex:)

. So you just use it on your sharded control like this:



self.viewPicker.setTitle("Description", forSegmentAtIndex:0)
self.viewPicker.setTitle("Location", forSegmentAtIndex:1)

      

+3


source


For Swift 3.0 use:

 self.viewPicker.setTitle("Description", forSegmentAt: 0)
 self.viewPicker.setTitle("Location", forSegmentAt: 1)

      

0


source







All Articles