Swift IOS - 使用UIPickerView和键盘

时间:2015-04-26 00:36:30

标签: ios swift uipickerview

在我的应用程序中,当用户点击UITextField时,他应该能够从UIPickerView中获取值或使用键盘输入自己的值。

在用户体验和易于实施方面,最好的方法是什么?

带工具栏的UIPickerView已经实现。

我很欣赏这方面的最佳建议和切换键盘的示例代码< - > pickerview。

我尝试过添加按钮"显示键盘"在pickerview的工具栏上添加以下代码:

func showKeyboard() {
    selectedTextField.inputView = nil
}

但是点击此按钮不会做任何事情。另外,我不确定它在用户体验方面是一个好方法。

1 个答案:

答案 0 :(得分:0)

以下是解决方案:

var useKeyboard:Bool = true
func showKeyboard() {
    if useKeyboard {
        useKeyboard = false
        selectedTextField.inputView = nil
        selectedTextField.reloadInputViews()
        selectedTextField.keyboardAppearance = UIKeyboardAppearance.Default
        selectedTextField.keyboardType = UIKeyboardType.Default
    } else {
        useKeyboard = true
        selectedTextField.inputView = nil
        selectedTextField.reloadInputViews()
        createPicker(selectedTextField)
        selectedTextField.resignFirstResponder()
        selectedTextField.becomeFirstResponder()
    }
}

// That's my custom picker - adjust whatever you need
func createPicker(sender: UITextField){
    selectedTextField = sender

    // Create picker view
    var newPickerView: UIPickerView
    newPickerView = UIPickerView(frame: CGRectMake(0, 200, view.frame.width, 300))
    newPickerView.backgroundColor = .whiteColor()

    // Only for UIPickerView
    newPickerView.showsSelectionIndicator = true
    newPickerView.delegate = self
    newPickerView.dataSource = self

    // Create toolbar
    var toolBar = UIToolbar()
    toolBar.barStyle = UIBarStyle.Default
    toolBar.translucent = true
    toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
    toolBar.sizeToFit()

    // Create buttons
    var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker")
    var spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
    var cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelPicker")
    var customButton = UIBarButtonItem(title: "Keyboard", style: UIBarButtonItemStyle.Plain, target: self, action: "showKeyboard")

    // Assign buttons to toolbar
    toolBar.setItems([cancelButton, spaceButton, customButton, doneButton], animated: false)
    toolBar.userInteractionEnabled = true

    // Add pickerview and toolbar to textfield
    sender.inputView = newPickerView
    sender.inputAccessoryView = toolBar
}
func donePicker() {
    useKeyboard = true
    selectedTextField.resignFirstResponder()
}
func cancelPicker() {
    useKeyboard = true
    selectedTextField.resignFirstResponder()
}