如何以编程方式创建多个pickerviews

时间:2016-05-23 17:29:42

标签: ios swift uipickerview

我正在尝试为所选的每个文本框创建单独的选择器视图。到目前为止,我得到的最接近的是每个文本框都有相同的选择视图,这些文本框需要各自独立的项目列表供选择。

class MainViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate {

var dogBreedPickerArray = ["German Shepherd", "Huskie", "cray cray"]
var catBreedPickerArray = ["savanna", "cheetoh", "bengal"]
var maleFemalePickerArray = ["Male", "Female"]

var dogBreedPicker = UIPickerView()

var dogBreedPicker = UIPickerView()
var catBreedPicker = UIPickerView()
var maleFemalePicker = UIPickerView()

@IBOutlet var dogBreedTextBox: UITextField!
@IBOutlet var catBreedTextBox: UITextField!
@IBOutlet var maleFemaleTextBox: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    dogBreedPicker.delegate = self
    dogBreedPicker.dataSource = self
    dogBreedTextBox.inputView = dogBreedPicker

    dogBreedTextBox.delegate = self
                            }
// dog picker functions
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
    }
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return dogBreedPickerArray.count
    }
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    petBreedTextBox.text = dogBreedPickerArray[row]
    }
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return dogBreedPickerArray[row]
    }
}

1 个答案:

答案 0 :(得分:0)

它只是一个例子可能对你有所帮助 选择任何文本字段后,将文本字段标签选择为选择器并重新加载组件。

// variable
var heightInch:[Int] = [Int]()
var heightfeet:[Int] = [Int]()
var heightCms:[Int] = [Int]()
delegate methods
  func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        if picker.tag == 1{
            return 2
        }else{
            return 1
        }
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if picker.tag == 1{
            switch component {
            case 0:
                return heightfeet.count
            default:
                return heightInch.count
            }

        }else{
            return heightCms.count
        }
    }
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if picker.tag == 1{
            switch component {
            case 0:
                return String(heightfeet[row])
            default:
                return String(heightInch[row])
            }
        }else{
            return String(heightCms[row])
        }