Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set title above each component of a UIPickerView?

I implemented a UIPickerview with 2 components. I want to set a title above each one. How can I do that?

I don't want do place a separate label above the picker.

like image 604
Obstn Avatar asked Nov 07 '22 13:11

Obstn


1 Answers

I often add an additional component to my UIPickerView with just one row and set that row's title to the header for the next component.

For example for an "hours and minutes" UIPickerView.

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 4 //2 headers and 2 values
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if component == 0 {
       return 1 //hours header
    } else if component == 1 {
       return 100 //hours
    } else if component == 2{
       return 1 //minutes header
    } else {
       return 4 //minutes
    }
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if component == 0 {
        return "Hours:" //header
    } else if component == 1 {
        return "\(row + 1)" //value
    } else if component == 2 {
        return "Minutes:" //header
    } else if component == 3 { 
        return "\(row * 15)" //value
    }
    return nil
}

The result will be this:

Result image

like image 174
Shadi Habiballah Avatar answered Nov 14 '22 21:11

Shadi Habiballah