我创建了两个按钮。一个称为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
按钮时,输入视图不会恢复为数字键盘并保持为选择器。有什么建议吗?
答案 0 :(得分:1)
尝试
func wieghtResponse(){
userInput.inputView = nil // reset your input view for weight input
userInput.keyboardType = UIKeyboardType.numberPad
userInput.becomeFirstResponder()
}