输入视图不会更改为UITextField

时间:2017-07-05 14:25:16

标签: ios swift uitextfield

我创建了两个按钮。一个称为Weight,另一个称为Age。这两个按钮都将第一个响应者设置为相同的UITextField。但是,如果触摸Weight按钮,键盘类型将变为数字键盘;如果触摸Age按钮,键盘类型将变为UIPickerVIew。以下是代码:

@IBOutlet var weightButton: UIButton!
@IBOutlet var ageButton: UIButton!
@IBOutlet var userInput: UITextField!

let agePicker = UIPickerView()
let ageAsString =  ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"]
var selectedAge: Double?

override func viewDidLoad() {
    super.viewDidLoad()
    createAgePicker()
}

//ButtonsClicked
@IBAction func weightSearch(_ sender: Any) {
    wieghtResponse()
}

@IBAction func ageSearch(_ sender: Any) {
    ageResponse()
}

func userInputResponse() {
    userInput.inputView = nil
    if weightButton.isTouchInside {
        userInput.inputView = nil
        userInput.keyboardType = UIKeyboardType.numberPad
        userInput.becomeFirstResponder()
    } else if ageButton.isTouchInside {
        userInput.inputView = nil
        userInput.inputView = agePicker
        userInput.becomeFirstResponder()
    }

//CreateAgePicker
func createAgePicker() {
    agePicker.delegate = self
    agePicker.backgroundColor = .white
    agePicker.tintColor = .clear
}
//Components
@available(iOS 2.0, *)
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
//Rows
@available(iOS 2.0, *)
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return ageAsString.count
}
//Labels
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return ageAsString[row]
}

我遇到的问题是,当我点击Age按钮时,选择器视图会加载。但是,当我单击Weight按钮时,输入视图不会恢复为数字键盘并保持为选择器。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

尝试

func wieghtResponse(){
    userInput.inputView = nil // reset your input view for weight input
    userInput.keyboardType = UIKeyboardType.numberPad
    userInput.becomeFirstResponder()
}