如何强制PickerView默认为数组项[0]

时间:2015-06-05 20:44:58

标签: ios arrays swift uipickerview

我一直在寻找两天,试图找到答案。我甚至可能没有正确地提出这个问题,所以请原谅我,如果是这样的话。

我希望我的数据选择器默认为该textField的数据源数组的第[0]项。目前,我没有看到加载pickerView时如何选择所选数组项的一致性。我有一个空白("")作为数组中的第一项,并认为用户会在pickerView中看到一个空白作为默认项目,其后包含所有其他项目。

如何强制pickerView显示""数组(每个数组中的第[0]项)作为pickerView加载时的默认选择值并显示给用户?

以下是pickerViews的代码:

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return self.activeDataArray.count
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
    return self.activeDataArray[row] as! String
}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if activeDataArray == personnelName {
        enterPersonnelName.text = personnelName[row] as String
    }
    else if activeDataArray == drugID {
        enterDrugID.text = drugID[row] as String
    }
    else if activeDataArray == packageNumber {
        enterPackageNumber.text = packageNumber[row] as String
        enterQty.text = quantity[0]
        enterExpDate.text = expDate[0]
    }
    //put pickerView away
    self.view.endEditing(true)
}

编辑:调用pickerView的代码

func textFieldDidBeginEditing(textField: UITextField) {
    activeDataArray == [] //clear out the clicked field data array
    if textField == enterPersonnelName {
        activeDataArray = personnelName
    } else
        if textField == enterDrugID {
            activeDataArray = drugID
    } else
        if textField == enterPackageNumber {
            activeDataArray = packageNumber
    } else
        if textField == enterQty {
            activeDataArray = quantity
    } else
        if textField == enterExpDate {
            activeDataArray = expDate
    }
    dataPickerView.reloadAllComponents() //clear out components of the dataPickerView
    dataPickerView.hidden = false
}

2 个答案:

答案 0 :(得分:1)

Selecting Rows in the View Picker

override func viewDidLoad() {
    super.viewDidLoad()
    pickerView.delegate = self
    pickerView.selectRow(0, inComponent: 0, animated: false)
}

答案 1 :(得分:0)

我这样做是为了解决这个问题:

    override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    pickerview.dataSource = self
    pickerview.delegate = self
    pickerviewLabel.text = pickerviewArray[0]
    }

我在UIPickerView

之后声明了数组
    @IBOutlet weak var pickerview: UIPickerView!
    let pickerviewArray = ["x","y","z","k"]