简体   繁体   中英

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?

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

}

You can just pass the only index into a variable like:

detailView.activeIndex = 1

And in the next view controller, you can simply set segment index in ViewDidLoad().

Note: It's crashing in your given question because at that point segment controller is nil.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM