Search code examples
iosswift3uiimageuipickerview

how to add uiimage to uipickerview programmatically swift 3


I created UIPickerView programmatically in controller and I need to add an image to UIPickerView with corresponding label. When I created UIImageView programmatically and added to UIPickerView an error is coming saying that, UIImage cannot be added to UIPickerView.

How can I solve this problem. Thanks In advance


Solution

  • func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView {
    
        var myView = UIView(frame: CGRectMake(0, 0, pickerView.bounds.width, 60))
    
        var ImageView = UIImageView(frame: CGRectMake(0, 0, pickerView.bounds.width, 50))
    
        var row = String()
        switch row {
        case 0:
            row = “animal1”
            ImageView.image = UIImage(named:"animal1.jpg")
        case 1:
            row = “animal2”
            ImageView.image = UIImage(named:"animal2.jpg")
        case 2:
            default:
            rowString = "Error: too many rows"
            ImageView.image = nil
        }
        myView.addSubview(ImageView)
    
        return myView
    }