小编典典

如何在Swift的UI PickerView组件中显示图像?

swift

我正在尝试在Swift
PickerView中使用图像。我不知道如何使图像实际出现在组件中。我知道如何使用带有titleForRow函数的Strings来执行此操作,但是我不知道如何使用图像来执行此操作。到目前为止,这是我的代码:

import UIKit
class ViewController: UIViewController, UIPickerViewDelegate {

    @IBOutlet weak var pickerView: UIPickerView!


    var imageArray: [UIImage] = [UIImage(named: "washington.jpg")!,
        UIImage(named: "berlin.jpg")!, UIImage(named: "beijing.jpg")!,
        UIImage(named: "tokyo.jpg")!]



    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    // returns the number of 'columns' to display.
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{

        return 1

    }

    // returns the # of rows in each component..
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        return imageArray.count
    }



}// end of app

阅读 338

收藏
2020-07-07

共1个答案

小编典典

您将需要为UIPickerViewDelegate协议实现更多的委托方法。特别是rowHeight委托方法和viewForRow委托方法。

就像是:

// MARK: UIPickerViewDataSource

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return 2
}

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


// MARK: UIPickerViewDelegate

func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView {

    var myView = UIView(frame: CGRectMake(0, 0, pickerView.bounds.width - 30, 60))

    var myImageView = UIImageView(frame: CGRectMake(0, 0, 50, 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:
        default:
        rowString = "Error: too many rows"
        myImageView.image = nil
    }
    let myLabel = UILabel(frame: CGRectMake(60, 0, pickerView.bounds.width - 90, 60 ))
    myLabel.font = UIFont(name:some font, size: 18)
    myLabel.text = rowString

    myView.addSubview(myLabel)
    myView.addSubview(myImageView)

    return myView
}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

   // do something with selected row
}

请注意,标签布局等仅用于演示,需要进行调整,或者最好使用自动布局ect。

2020-07-07