Search code examples
iosswiftuisegmentedcontrol

For an alertController: what is the sourceView of a selected segment in a UISegmentedControl


I have an UISegmentedControl with 4 segments. Some of these segments instantiate an UIAlertController when selected by the user.

On the UIAlertController, you can set popoverPresentationController?.sourceView to let the alert controller point to the view of origin, which will be used on larger devices like an iPad.

I try to pass the UISegmentedControl, which works, but the anchor is always the top left corner of the segmented control - not the segment that was selected.

I'd like to use the actual segment of the UISegmentedControl as a sourceView, but there is no array on UISegmentedControl that contains the segments.

There is a subviews property that holds an array of views. The number corresponds to the number of segments, so I though I found my solution. But if I assign:

alertController.popoverPresentationController?.sourceView = segmentedControl.subviews[2]

...for the 3rd segment, it sometimes works and sometimes doesn't. It looks like this array is not always in the order of segments on the screen.

How can I find the correct subview to use?


Solution

  • I found a solution:

    alertController.popoverPresentationController?.sourceView = (segmentedControl.subviews.sorted { $0.frame.origin.x < $1.frame.origin.x })[segmentedControl.selectedSegmentIndex]
    

    This will first sort the views in the order of their x coordinate. Then I can use the segmentedControl.selectedSegmentIndex as an index.