我正在Swift中迈出第一步,我想制作一个转换应用程序。 我想使用2个pickerviews,一个用于选择原点类型,另一个用于选择目标类型。 问题是我无法使2个pickerviews工作...我想要的是点击一个文本字段并显示第一个选择器视图然后单击其他文本字段并显示其他选择器视图但发生的事情是它始终打开第一次挑选。 这是代码:
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
@IBOutlet weak var txtOrigem: UITextField!
@IBOutlet weak var txtDestino: UITextField!
@IBOutlet weak var pickerpeso: UIPickerView! = UIPickerView()
@IBOutlet weak var pickerpeso2: UIPickerView! = UIPickerView()
var pesos = ["Escolher Opção","Gramas", "Quilogramas", "Toneladas", "Libras", "Onças"]
var pesos2 = ["ola","Gramas", "Quilogramas", "Toneladas", "Libras", "Onças"]
override func viewDidLoad() {
super.viewDidLoad()
pickerpeso.delegate = self
pickerpeso2.delegate = self
txtOrigem.delegate = self
txtDestino.delegate = self
pickerpeso.tag = 0
pickerpeso2.tag = 1
pickerpeso.hidden = true;
pickerpeso2.hidden = true;
txtOrigem.text = pesos[0]
txtDestino.text = pesos2[0]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView.tag == 0 {
return pesos.count
}
else if pickerView.tag == 1 {
return pesos2.count
}
return 1
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView.tag == 0 {
return pesos[row]
}
else if pickerView.tag == 1 {
return pesos2[row]
}
return ""
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView.tag == 0 {
txtOrigem.text = pesos[row]
}
else if pickerView.tag == 1 {
txtDestino.text = pesos2[row]
}
pickerpeso.hidden = true
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
pickerpeso.hidden = false
return false
}
}
希望有人可以帮助我。抱歉我的英语不好。 提前谢谢!
答案 0 :(得分:3)
问题是你的textFieldShouldBeginEditing方法。您只需为其中一个pickerView设置.hidden属性。将标记添加到两个textFields(如2和3)并将方法更改为:
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if textField.tag == 2 {
pickerpeso.hidden = false
pickerpeso2.hidden = true
} else if textField.tag == 3 {
pickerpeso.hidden = true
pickerpeso2.hidden = false
}
return false
}
取决于textField将获得焦点的一个pickerView被隐藏而另一个是可见的。