如何在UIPickerView的每个组件上方设置标题?

时间:2017-12-01 13:11:15

标签: ios swift uipickerview

我实现了一个包含2个组件的UIPickerview。我想在每个上面设置一个标题。我怎么能这样做?

我不想在选择器上方放置单独的标签。

2 个答案:

答案 0 :(得分:1)

我经常在我的UIPickerView中仅添加一行,并将该行的标题设置为下一个组件的标题。

例如,“小时和分钟” 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
}

结果将是这样:

Result image

答案 1 :(得分:0)

 func setHeadersForPickerView() {
    let labelWidth = deliveryPicker.frame.width / CGFloat(deliveryPicker.numberOfComponents)
    for index in 0..<pickerHeaders.count {
        let label: UILabel = UILabel(frame: CGRect(x: deliveryPicker.frame.origin.x + (labelWidth * CGFloat(index)), y: 10, width: labelWidth + 40, height: 20))
        label.text = pickerHeaders[index]
        label.textAlignment = .center
        deliveryPicker.addSubview(label)
    }
}