在Swift中为UIPickerView委派方法

时间:2014-06-09 18:29:27

标签: ios objective-c swift

刚开始使用Swift并且无法调用UIPickerView的委托方法

到目前为止,我已将UIPickerViewDelegate添加到我的类中,如下所示:

class ExampleClass: UIViewController, UIPickerViewDelegate

我还创建了我的UIPickerView并为其设置了委托:

@IBOutlet var year: UIPickerView
year.delegate = self

现在我无法将以下内容转换为Swift代码:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:11)

这实际上是UIPickerViewDataSource协议中的一种方法,因此您需要确保同时设置选择器视图的dataSource属性:year.dataSource = self。 Swift本地方式似乎是在类扩展中实现协议,如下所示:

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)
}

答案 1 :(得分:0)

委托人不负责调用该方法。相反,它由UIPickerView的数据源调用。这些是您需要实现的UIPickerView数据源调用的两个函数:

// 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

为确保调用这些函数,您的类还应实现数据源协议:

class ExampleClass: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource

应设置您的选择器数据源:

year.dataSource = self