iosswiftuikitsegment

Custom Segmented Control setIndex Thread 1: Fatal error: Index out of range” when I setselected index


I am using this Custom Segmented Controlcode in one of my View. I have one issue when I tried to setIndex I make it public and I passed the number of selected index I get this error "Thread 1: Fatal error: Index out of range” when I set selected index"

  public func setIndex(index: Int) {
        buttons.forEach({ $0.setTitleColor(textColor, for: .normal) })
        let button = buttons[index]
        selectedIndex = index
        button.setTitleColor(selectorTextColor, for: .normal)
        let selectorPosition = frame.width/CGFloat(buttonTitles.count) * CGFloat(index)
        UIView.animate(withDuration: 0.2) {
            self.selectorView.frame.origin.x = selectorPosition
        }
    }

Solution

  • Before moving to the functionality, first check wether the index is within the buttons array range

     if index > buttons.count - 1 {
       // Index out of range.
       return
     }