I use the Xcode 8 and swift 2.3, but I met a problem the UIPickerView.dataSource = (self as! UIPickerViewDataSource)
doesn't work when I try to use func of UIPicker
, this is my code:
import UIKit
class ViewController: UIViewController {
let Num = ["1","2","3","4","5","6"]
@IBOutlet weak var UIPicker: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
func numberOfRows(inComponent component: Int) -> Int {return 1}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {return Num.count}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {return Num[row]}
UIPicker.dataSource = (self as! UIPickerViewDataSource)
UIPicker.delegate = (self as! UIPickerViewDelegate)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
When I run my code, Xcode warning the code:
Could not cast value of type 'test.ViewController' (0x1000bd8c0) to 'UIPickerViewDataSource' (0x1ab289738). 2016-06-29 15:33:35.079300 test[474:98176] Could not cast value of type 'test.ViewController' (0x1000bd8c0) to 'UIPickerViewDataSource' (0x1ab289738).
Add UIPickerViewDataSource
and UIPickerViewDelegate
to the class declaration:
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate
and don't use type casting using self
:
override func viewDidLoad() {
super.viewDidLoad()
UIPicker.dataSource = self
UIPicker.delegate = self
}
Also you must move your methods out of viewDidLoad
function, and correct them a bit:
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {return 1}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {return Num.count}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {return Num[row]}
Note that I highly recommend you to rename your Num
and UIPicker
properties to num
and picker
, so you will not mix them with class names
Upd: full ViewController
code:
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
let Num = ["1","2","3","4","5","6"]
@IBOutlet weak var UIPicker: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
UIPicker.dataSource = self
UIPicker.delegate = self
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {return 1}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {return Num.count}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {return Num[row]}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With