I am trying to use images in a Swift PickerView. I don't know how to get the images to actually appear in the component. I know how to do this using Strings with the titleForRow function but I don't know how to do this using images. Here is my code so far:
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
I had this same question and did some research until I figured it out. Here's an example that works great for me. Just make sure your images in the Assets folder are all named the same as your case strings and you'll be set!
You do not need to subclass
UIPickerView
(and in fact that is probably not a wise view to subclass anyhow). Instead you need to have an object that implements theUIPickerViewDelegate
protocol. Within this object you would implement the methodThis method provides the individual components' views. Within that method you would return the appropriate value from your image array.
You will need to implement a couple more the delegate methods for the UIPickerViewDelegate protocol. In particular a rowHeight delegate method and a viewForRow delegate method.
Something like:
Note that the label layout etc is just for demonstration, would need to be tweaked, or probably better to use Auto Layout ect.
Making switch statements could be tedious when dealing with a lot of stuff.
Instead, use a for loop like this