Search code examples
iosswiftuitextfield

Input View Not Changing For UITextField


I have created two buttons. One called Weight and the other Age. Both of these buttons set the same UITextField as a first responder. However, if the Weight button is touched, the keyboard type becomes a number pad; if the Age button is touched, the keyboard type becomes a UIPickerVIew. Here is the code below:

@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]
}

The issue I am having is that when I click on the Age button, the picker view loads. However, when I click back on the Weight button, the input view doesn't revert back to a number pad and stays as the picker. Any advice?


Solution

  • Try

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