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?
source to share
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!
source to share
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)
source to share