所以我试图做到这一点,所以当我单击键盘上的reutrn / done键时,键盘将隐藏,但是由于某些原因,当我尝试委派两个文本字段时,每当我单击nameTextField时,它将认为im按下jobTextField并显示该pickerView。有人知道吗?
ViewController代码
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource {`
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var jobTextField: UITextField!
@IBOutlet weak var jobPickerView: UIPickerView!
@IBAction func setupDoneButton(_ sender: Any) {
if (nameTextField.text?.isEmpty == false) {
defaults.set(nameTextField.text, forKey: "name")
defaults.set(jobTextField.text, forKey: "job")
}
}
let defaults = UserDefaults.standard
let jobs = ["Real Estate Agent","Retail","Teacher", "Student", "Other"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
jobPickerView.isHidden = true;
jobPickerView.delegate = self
jobPickerView.dataSource = self
jobTextField.delegate = self
nameTextField.delegate = self
nameTextField.returnKeyType = UIReturnKeyType.done
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare (for segue: UIStoryboardSegue, sender: Any!) {
if (segue.identifier == "setupDoneButtonSegue") {
let svc = segue.destination as! SecondViewController
svc.firstDataPassed = nameTextField.text
svc.secondDataPassed = jobTextField.text
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return jobs.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return jobs[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
jobTextField.isHidden = false;
jobPickerView.isHidden = true;
jobTextField.text = jobs[row];
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
jobTextField.isHidden = true
jobPickerView.isHidden = false;
return false
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
}
答案 0 :(得分:1)
在为两个字段都设置UITextFieldDelegate
时,您需要在textFieldShouldBeginEditing
中添加条件,以便仅对pickerView
显示jobTextField
。
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
jobTextField.isHidden = false
jobPickerView.isHidden = true
if jobTextField == textField {
jobTextField.isHidden = true
jobPickerView.isHidden = false
return false
}
return true
}
答案 1 :(得分:1)
在Aspect Ratio
中输入时,您需要验证使用的是textField。
有一个例子:
textFieldShouldBeginEditing
希望对您有帮助。