C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ViewController: For this tutorial do all our work in ViewController.swift. We will add protocols that ViewController implements.
Example ViewController: Swift
//
// ViewController.swift
// ExampleTime11
//
// ...
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBOutlet weak var simplePicker: UIPickerView!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Array: The data array has three strings. These will be used to populate the UIPickerView.
DataSource, delegate: Assign these properties for the "simplePicker" to the "self" class. Both must be assigned.
Funcs: Just paste the funcs into your file at first. These are required to indicate components (columns) and rows for the Picker View.
Example ViewController: Swift
//
// ViewController.swift
// ExampleTime11
//
// ...
//
import UIKit
// Change ViewController to implement 2 protocols.
// ... UIPickerViewDelegate is needed.
// ... UIPickerViewDataSource is needed.
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
// 3 items for the picker.
var data = ["cat", "bird", "frog"]
override func viewDidLoad() {
super.viewDidLoad()
// Set dataSource and delegate to this class (self).
self.simplePicker.dataSource = self
self.simplePicker.delegate = self
}
// Outlet.
@IBOutlet weak var simplePicker: UIPickerView!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
// Column count: use one column.
return 1
}
func pickerView(pickerView: UIPickerView,
numberOfRowsInComponent component: Int) -> Int {
// Row count: rows equals array length.
return data.count
}
func pickerView(pickerView: UIPickerView,
titleForRow row: Int,
forComponent component: Int) -> String? {
// Return a string from the array for this row.
return data[row]
}
}
Tip: When an iOS program encounters a UIPickerView it calls the methods you provide in these funcs to display text.
Here: We see the strings from our "data" array as rows in the UIPickerView. We can click on different rows to select them.