Search code examples
iosswiftsegueuisegmentedcontrol

Set segmented control's index based on segue


I am going form one controller to another using several different uibuttons and segues. I want to set my segmented control to start at a specified index based on the segue used. I have attempted the code below but receive an error when I run the app.

Code:

if segue.identifier == "watchedSegue" {
        if let detailView = segue.destination as? ListView {
            detailView.watchList = watchList
            detailView.watchedList = watchedList
            detailView.listSeg.selectedSegmentIndex = 1 //Error: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
        }
    }

Why am I receiving this error when running the app? What is the preferred way of setting default index based on segue?


Solution

  • Using the comment from M Abubaker Majeed I Replaced:

    detailView.listSeg.selectedSegmentIndex = 1
    

    with:

    detailView.segIndex = 1
    

    Then placed this into the segmented view controller:

    var segIndex = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
    listSeg.selectedSegmentIndex = segIndex
    
    }