Xavi Valero
Xavi Valero

Reputation: 2057

Make a segment of a segmented control invisible

Is it possible to make one segment of a segmented control invisible?

Upvotes: 16

Views: 8740

Answers (4)

regina_fallangi
regina_fallangi

Reputation: 2198

None of the results above worked for me. The one reducing the width did not work because I had set

control.segmentDistribution = .fillEqually

What worked for me was resetting the segment control's count. Here an example when the data source for the segments is ["Option 1", "Option 2", "Option 3"]. Imagine you want to remove "Option 2":

var segmentDataSource = ["Option 1", "Option 2", "Option 3"]

segmentDataSource.remove(at: 1)

let oldSelectedSegment = control.selectedSegment

control.segmentCount = segmentDataSource.count
control.selectedSegment = max(0, oldSelectedSegment - 1)
for (index, option) in segmentDataSource.enumerated() {
    control.setLabel(option, forSegment: index)
}

Upvotes: 0

Jaywant Khedkar
Jaywant Khedkar

Reputation: 6121

Yes ,try this it's working for me ,It's only one line of code ,

Objective C

 [self.segmentControl removeSegmentAtIndex:0 animated:NO];

Swift

 segmentControl.removeSegment(at: 0, animated: false)

The code remove 0 index segment and show only one segment invisible.

Hope this helps.

Upvotes: 0

Tibidabo
Tibidabo

Reputation: 21571

You can't hide it but you can make its width very very small which will make it invisible for the user. It has to be > 0 because 0 = automatic width.

[yourSegmentedControl setWidth:0.1 forSegmentAtIndex:1];

To be in the safe side, also disable it to reduce the chance of selection to zero.

[mapTypeSC setEnabled:NO forSegmentAtIndex:1];

Upvotes: 21

EmptyStack
EmptyStack

Reputation: 51374

Though it seems there is no way to hide a segment in a segment control, you could remove a segment from the segment control using removeSegmentAtIndex:animated: method. You need either insertSegmentWithImage:atIndex:animated: or insertSegmentWithTitle:atIndex:animated: method to insert the segment again.

Instead of hiding/showing a segment you could consider enabling/disabling it using setEnabled:forSegmentAtIndex: method.

Upvotes: 16

Related Questions