Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 247
Jonathan Allen Grant Avatar asked Mar 15 '23 07:03

Jonathan Allen Grant


2 Answers

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!

like image 178
Jiri Trecak Avatar answered Mar 24 '23 19:03

Jiri Trecak


The UISegmentControl has a method that lets you change the labels individually called: setTitle(_:forSegmentAtIndex:). So you just use it on your segmented control like so:

self.viewPicker.setTitle("Description", forSegmentAtIndex:0)
self.viewPicker.setTitle("Location", forSegmentAtIndex:1)
like image 45
dudeman Avatar answered Mar 24 '23 19:03

dudeman