Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate Methods in Swift for UIPickerView

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

like image 201
user3723426 Avatar asked Jun 09 '14 18:06

user3723426


People also ask

What is the purpose of the delegate of a Uipicker view object?

Use your picker view delegate (an object that adopts the UIPickerViewDelegate protocol) to provide views for displaying your data and responding to user selections.

What is Pickerview?

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.


1 Answers

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)
}
like image 98
Nate Cook Avatar answered Oct 02 '22 20:10

Nate Cook