Search code examples
iosswiftuisegmentedcontrol

Select which case is selected for UISegmentedControl


I am using an UISegmentedControl and have a switch with two cases set for each option. As of now the first case is selected when the view controller loads.

EDIT: How would I set the second case to be selected instead of the first only when the count is higher than the first.

Here is the code:

func collectionView(_ _collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    var count = 0

    switch(filmSeg.selectedSegmentIndex) {

    case 0:

        count = one.count 

        break

    case 1:

        count = two.count

        break

    default:
        break

    }

    return count

}

Solution

  • As you can see here on the Apple Developer page, selectedSegmentIndex is declared as such:

    var selectedSegmentIndex: Int { get set }
    

    This means you can just put something like this in your viewDidLoad:

    filmSeg.selectedSegmentIndex = 1