如何以编程方式将uiimage添加到uipickerview swift 3

时间:2017-02-10 06:08:31

标签: ios swift3 uiimage uipickerview

我在控制器中以编程方式创建了UIPickerView,我需要将图像添加到UIPickerView并带有相应的标签。当我以编程方式创建UIImageView并添加到UIPickerView时,会出现错误,UIImage无法添加到UIPickerView

我该如何解决这个问题。在此先感谢

2 个答案:

答案 0 :(得分:3)

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
}

答案 1 :(得分:2)

在Swift 3中,尝试以下代码:

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    let myView = UIView(frame: CGRect(x: 0, y: 0, width: pickerView.bounds.width - 30, height: 60))
    let myImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
    var rowString = String()
    switch row {
    case 0:
        rowString = "Washington"
        myImageView.image = UIImage(named:"washington.jpg")
    case 1:
        rowString = "Beijing"
        myImageView.image = UIImage(named:"beijing.jpg")
    case 2: break
    default:
        rowString = "Error: too many rows"
        myImageView.image = nil
    }
    let myLabel = UILabel(frame: CGRect(x: 60, y: 0, width: pickerView.bounds.width - 90, height: 60))
    myLabel.text = rowString

    myView.addSubview(myLabel)
    myView.addSubview(myImageView)
    return myView
}