How do I use multiple picker views with different data sources in the same view?

后端 未结 3 1939
孤城傲影
孤城傲影 2020-12-18 09:06

I have a view with three picker views in it. Two of the picker views have the same data, an array with the numbers 1 to 100. The third picker view has an array with a list

3条回答
  •  情话喂你
    2020-12-18 09:25

    If you IBOutlet the connections, you don't need the Tags. All IBOutlet should be weak, We generally use weak for IBOutlets (UIViewController's Childs).This works because the child object only needs to exist as long as the parent object does.

    If you're using storyboard or Nib for UIPickerView, you don't need to do the allocation for UIPickerView.

    Try this:

    @IBOutlet weak var trackPickerView: UIPickerView!
    @IBOutlet weak var layoutWidthPickerView: UIPickerView!
    @IBOutlet weak var layoutLengthPickerView: UIPickerView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        trackPickerView.delegate = self
        layoutWidthPickerView.delegate = self
        layoutLengthPickerView.delegate = self
    }
    
    let numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100"]
    
    let manufacturers = ["Atlas True Track", "Atlas Code 100", "Atlas Code 83", "Bachmann Nickel Silver", "Bachmann Steel Alloy", "Kato", "Life-Like Trains Code 100", "LIfe-Like Trains Power-Loc", "Peco Code 100", "Peco Code 83", "Peco Code 75", "Shinohara Code 100", "Shinohara Code 70", "Walthers"]
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    
        if pickerView == layoutWidthPickerView || pickerView == layoutLengthPickerView {
            return numbers[row]
        }
    
        return manufacturers[row]
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    
        if pickerView == layoutWidthPickerView || pickerView == layoutLengthPickerView {
            return numbers.count
        }
    
        return manufacturers.count
    
    }
    

    Output:

提交回复
热议问题