首页 > 解决方案 > 对于 alertController:UISegmentedControl 中选定段的 sourceView 是什么

问题描述

我有一个UISegmentedControl4 段。这些段中的一些UIAlertController在用户选择时实例化。

在 上UIAlertController,您可以设置popoverPresentationController?.sourceView让警报控制器指向原点视图,这将用于 iPad 等较大的设备。

我尝试通过UISegmentedControl,它有效,但锚始终是分段控件的左上角 - 而不是被选中的段。

我想使用的实际段UISegmentedControl作为 sourceView,但没有UISegmentedControl包含这些段的数组。

有一个包含视图数组的子视图属性。该数字对应于段数,所以我虽然找到了解决方案。但如果我分配:

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

...对于第三段,它有时有效,有时无效。看起来这个数组并不总是按屏幕上的段顺序排列。

如何找到要使用的正确子视图?

标签: iosswiftuisegmentedcontrol

解决方案


我找到了一个解决方案:

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

这将首先按照 x 坐标的顺序对视图进行排序。然后我可以使用segmentedControl.selectedSegmentIndex作为索引。


推荐阅读