下拉样式UIPickerView?

Drop-down style UIPickerView?

我想知道如何让 UIPickerView 在点击下拉样式按钮后从屏幕底部向上滑动。如下图所示:

我 运行 在我经常使用的应用程序中经常使用这种类型的选择器视图,所以老实说,我希望通过设置 UIPickerView 来轻松找到这种选择器视图style 属性,或类似的东西。这甚至是 UIPickerView 还是我必须手动创建这种视图?

实现此目的的一种方法是使用普通 UITextField,然后将 UIPickerView 指定为该文本字段的 inputView。这样,当您点击文本字段时,键盘不会出现,而是您会看到选择器视图。

例子

首先声明一个正常的UIPickerView实例:

let yourPicker = UIPickerView()

UITextField 的出口:

@IBOutlet weak var yourTextField: UITextField!

在您的 viewDidLoad 中,您将元素连接在一起

yourPicker.delegate = self
yourPicker.dataSource = self
yourTextField.inputView = yourPicker

然后需要实现UIPickerViewDelegateUIPickerViewDataSource

所需的方法

终于。在 pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) 中,您更新文本字段的值:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
   yourTextField.text = yourDataArrayUsedInThePicker[row]
}

阅读更多

inputView的描述 https://developer.apple.com/library/content/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/InputViews/InputViews.html

一种比我更好的解释: Show UIPickerView text field is selected, then hide after selected

希望对你有所帮助。