Delegate methods in Swift for UIPickerView

Just getting started in Swift and not getting a delegate method call for UIPickerView

So far, I have added UIPickerViewDelegate to my class as follows:

class ExampleClass: UIViewController, UIPickerViewDelegate 

I also created my UIPickerView and set a delegate for it:

 @IBOutlet var year: UIPickerView year.delegate = self 

Now I just can't get the following into Swift code:

 - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView 

Any help would be appreciated

+7
ios objective-c swift
source share
2 answers

This is actually a method in the UIPickerViewDataSource protocol, so you need to make sure you also set the viewer property dataSource : year.dataSource = self . It seems that Swift-native's way is to implement protocols in class extensions, for example:

 class ExampleClass: UIViewController { // properties and methods, etc. } extension ExampleClass: UIPickerViewDataSource { // two required methods func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int { return 1 } func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int { return 5 } } extension ExampleClass: UIPickerViewDelegate { // several optional methods: // func pickerView(pickerView: UIPickerView!, widthForComponent component: Int) -> CGFloat // func pickerView(pickerView: UIPickerView!, rowHeightForComponent component: Int) -> CGFloat // func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! // func pickerView(pickerView: UIPickerView!, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString! // func pickerView(pickerView: UIPickerView!, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView! // func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) } 
+11
source share

The delegate is not responsible for calling this method. Instead, it is called by the UIPickerView data source. These are two functions called the UIPickerView data source that you must implement:

 // returns the number of 'columns' to display. func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int // returns the # of rows in each component.. func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int 

For these calls to be made, your class must also implement the data source protocol:

 class ExampleClass: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource 

And your selection data source should be installed:

 year.dataSource = self 
0
source share

All Articles