How can I make my UIPickerView Multiline in swift?

Jurian Amatsahip picture Jurian Amatsahip · Apr 18, 2016 · Viewed 7.2k times · Source

I have a UIPickerView how can I make it multiline? I have some long text.

Here is my code.

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    var returnResult: String = ""
    if pickerView.tag == 1 {
    //This picker has long text
        let position: UInt = UInt(row)
        returnResult = list.objectAtIndex(position).Description.Value;
    } else if pickerView.tag == 2 {
        returnResult =  questionTwoOptions[row]
    } else if pickerView.tag == 3 {
        returnResult = questionThreeOptions[row]
    } else {
        returnResult = ""
    }
    print(returnResult)
    return returnResult
}

Here is my viewForRow methode

func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
    let label = UILabel(frame: CGRectMake(0, 0, 400, 44));
    label.lineBreakMode = .ByWordWrapping;
    label.numberOfLines = 0;
    //view!.addSubview(label)
    return label;
}

Answer

HardikDG picture HardikDG · Apr 18, 2016

You can try like this with the custom view

func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
    let label = UILabel(frame: CGRectMake(0, 0, 400, 44));
    label.lineBreakMode = .ByWordWrapping;
    label.numberOfLines = 0;
    label.text = arr[row]
    label.sizeToFit()
    return label;
}

If you have content that can take more than two lines you can also set the row height

func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
    return 80
}