ios swiftui


Up until iOS 13, the options available for inline pickers felt limited. We could show the wheel inline, but that doesn’t look great in table views, lists, and forms. The other option was to use the navigation stack. But if we didn’t want to use the navigation stack, handling pickers could be painful.

直到iOS 13为止,内联选择器可用的选项都受到限制。 我们可以在线显示转轮,但是在表视图,列表和表单中看起来并不好。 另一个选择是使用导航堆栈。 但是,如果我们不想使用导航堆栈,则处理选择器可能会很痛苦。

Apart from those two options supported directly by iOS, many apps tried to solve this problem by showing the wheel in the keyboard area. Some apps even decided to use an action sheet, which in my opinion is a bad design choice.

除了iOS直接支持的两个选项外,许多应用程序还试图通过在键盘区域显示滚轮来解决此问题。 有些应用甚至决定使用操作表,我认为这是一个糟糕的设计选择。

Will iOS 14 help us solve this problem? If we look at the documentation for PickerStyle, there is no update for iOS 14. Where else can we look?

iOS 14可以帮助我们解决此问题吗? 如果我们查看PickerStyle的文档,则iOS 14没有更新。我们还能在哪里查看?

I was watching the Design with iOS Menus and Pickers session for WWDC 20 and there was a mention of using menus for selection.

我正在观看WWDC 20的“ 使用iOS菜单和选择器进行设计”会议 ,其中提到使用菜单进行选择。

Here’s how a simple menu looks in Xcode:

这是一个简单的菜单在Xcode中的外观:

Here’s how it translates to the iPhone:

这是如何转换为iPhone的:


iOS 14 screenshot of sample menu iOS 14示例菜单的屏幕截图

Well, this can solve the inline picker problem, but I found no help in the documentation regarding how to use it for selection.

好的,这可以解决内联选择器问题,但是我在文档中找不到有关如何使用它进行选择的帮助。

Here’s my attempt to use the menu as a picker:

这是我尝试将菜单用作选择器的尝试:


We can pass in an array of values that can be mapped to a View and an integer referring to the currently selected index.

我们可以传入一个可以映射到View的值数组和一个引用当前所选索引的整数。

The core work for using Menu happens between lines 30-53. When the menu is to be shown, we loop through the array and show the view for its respective index. Near the view for the selected index, we add a checkmark.

使用Menu的核心工作发生在第30-53行之间。 当显示菜单时,我们遍历数组并显示其相应索引的视图。 在所选索引的视图附近,我们添加了一个选中标记。

The initializer takes in an optional string, just like the good old Picker. If you want to show a name near the selected value, it will be helpful.

初始化程序采用一个可选字符串,就像旧的Picker 。 如果要在所选值附近显示名称,将很有帮助。


Our custom MenuPicker in action

我们自定义的MenuPicker在运行

This can work well in most cases where our old picker was not helpful. And to top it off, we can even do this in the navigation bar and it works the same.

在我们的旧选择器无济于事的大多数情况下,这可以很好地工作。 最重要的是,我们甚至可以在导航栏中执行此操作,并且效果相同。


Now, we can go ahead and use this new MenuPicker wherever we need an inline option to select from a list of values. The full code can be seen on GitHub.

现在,我们可以继续使用此新的MenuPicker在需要内联选项以从值列表中进行选择的任何地方使用。 完整的代码可以在GitHub上看到。

Happy coding!

编码愉快!


翻译自: https://medium.com/better-programming/using-ios-14s-menu-as-a-picker-in-swiftui-b036c772037

ios swiftui