Search code examples
arraysswiftuipickerview

How do I setUp a pickerView with 4 components, Arry? Swift


I tried a lot but it just shows me "?" in the rows of the four components. Is it possible to put a String at the first place in the Array Like as titles for the 4 components? I had the idea to change all the Integers in the arrays into Strings but it would takes me too long...

let componentOne = [1...1000]
    let componentTwo = [1...59]
    let componentThree = [1...59]
    let componentFour = [1...3]
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 4
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 {
            return 1000
        }
        if component == 1 {
            return 59
        }
        if component == 2 {
            return 59
        }
        if component == 3 {
            return 3
        }
        return component
    }
        
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> Int {
        if component == 0 {
            let row = componentOne[row]
            return 1000
            }
            if component == 1 {
                let row = componentTwo[row]
                return 59
                }
                if component == 2 {
                    let row = componentThree[row]
                    return 59
                    }
                    if component == 3 {
                        let row = componentFour[row]
                        return 10
                        }
        return row
                    }
    ```

Solution

  • You can't just change the delegate method. This is the correct one:

    func pickerView(_ pickerView: UIPickerView, 
                    titleForRow row: Int, 
                    forComponent component: Int) -> String?
    

    You have:

    func pickerView(_ pickerView: UIPickerView,
                    titleForRow row: Int,
                    forComponent component: Int) -> Int
    

    You must return a String? no matter what -- if you change the function's return type to Int, it doesn't match the protocol requirement.

    The good thing is that you can easily make a String from an Int. Just use String interpolation like this:

    /// Inside pickerView(_:titleForRow:forComponent:)
    
    let row = componentOne[row]
        return "\(1000)"
    }