Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISegmentedControl change number of segments programmatically

Is there a way to change the number of segments programmatically?

like image 256
Beppino66 Avatar asked Jul 24 '12 20:07

Beppino66


3 Answers

Yes, you can use

removeSegmentAtIndex:(NSUInteger) animated:(BOOL)

And

insertSegmentWithTitle:(NSString *) atIndex:(NSUInteger) animated:(BOOL)
like image 181
Scar Avatar answered Oct 02 '22 01:10

Scar


To replace the segments entirely, you can use the following function:

- (void)setSegments:(NSArray *)segments
{
    [segmentController removeAllSegments];

    for (NSString *segment in segments) {
        [segmentController insertSegmentWithTitle:segment atIndex:segmentController.numberOfSegments animated:NO];
    }
}

Hope this helps.

like image 33
Zorayr Avatar answered Oct 02 '22 03:10

Zorayr


And here's a little Swift extension to replace current segmentedControl with array of new values

Swift 3

extension UISegmentedControl {
    func replaceSegments(segments: Array<String>) {
        self.removeAllSegments()
        for segment in segments {
            self.insertSegmentWithTitle(segment, atIndex: self.numberOfSegments, animated: false)
        }
    }
}

Swift 4

extension UISegmentedControl {
    func replaceSegments(segments: Array<String>) {
        self.removeAllSegments()
        for segment in segments {
            self.insertSegment(withTitle: segment, at: self.numberOfSegments, animated: false)
        }
    }
}
like image 41
kernelpanic Avatar answered Oct 02 '22 02:10

kernelpanic