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?
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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With