Search code examples
swiftuisegmentedcontrol

Swift: UISegmentedControl last index is not selected


I have to select UISegmentedControl index programmatically on viewWillAppear().

switch shirtSize {
    case ProfilingPreferredShirtSize.xs.rawValue:
        shirtSizeSegmentedControl.selectedSegmentIndex = 0
    case ProfilingPreferredShirtSize.s.rawValue:
        shirtSizeSegmentedControl.selectedSegmentIndex = 1
    case ProfilingPreferredShirtSize.m.rawValue:
        shirtSizeSegmentedControl.selectedSegmentIndex = 2
    case ProfilingPreferredShirtSize.l.rawValue:
        shirtSizeSegmentedControl.selectedSegmentIndex = 3
    case ProfilingPreferredShirtSize.xl.rawValue:
        shirtSizeSegmentedControl.selectedSegmentIndex = 4
    default:
        break
}

When the last index (4) is selected, the corresponding segment is not graphically selected. When I manually tap on the last segment, it becomes selected but the valueChange callback is not called. This means that the the selectedSegmentIndex was already set and it's just a graphic bug. What can I do? For all the other values (0-3) it perfectly works.


Solution

  • Just try to refresh the layout:

    setNeedsLayout();