我创建了两个按钮。一个称为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按钮时,输入视图不会恢复为数字键盘,而是保持为选择器。有什么建议吗?

最佳答案

尝试

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

关于ios - UITextField的输入 View 未更改,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44928971/

10-16 19:37