Just getting started in Swift and having trouble calling the delegate methods for a UIPickerView
So far I have added the UIPickerViewDelegate to my class like so:
class ExampleClass: UIViewController, UIPickerViewDelegate
I have also created my UIPickerView and set the delegate for it:
@IBOutlet var year: UIPickerView
year.delegate = self
Now I am just having trouble turning the following into Swift code:
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
Any help would be appreciated
Use your picker view delegate (an object that adopts the UIPickerViewDelegate protocol) to provide views for displaying your data and responding to user selections.
A picker view can be defined as the view that shows a spinning wheel or slot machine to display one or more set of values so that the user can spin the wheel to select one. It is an instance of UIPickerView class which inherits UIView.
That's actually a method in the UIPickerViewDataSource
protocol, so you'll want to make sure you set your picker view's dataSource
property as well: year.dataSource = self
. The Swift-native way seems to be to implement protocols in class extensions, like this:
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)
}
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