我正在Swift中迈出第一步,我想开发一个转换应用程序。
我想使用2个pickerviews,一个选择原始类型,另一个选择目标类型。
问题是我无法使这2个pickerviews正常工作...我想要的是单击一个文本字段并显示第一个pickerview,然后单击另一个文本字段并显示另一个pickerview,但是发生的是它总是打开首先pickerview。
这是代码:
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
}
}
希望有人可以帮助我。对不起,我的英语不好。
提前致谢!
最佳答案
问题是您的textFieldShouldBeginEditing方法。您只是为pickerViews之一设置.hidden属性。将标签添加到两个textField中(例如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隐藏,而另一个则可见。