Swift中UIPickerView的代理方法

8

我刚开始学习Swift,但在调用UIPickerView的委托方法时遇到了麻烦。

目前为止,我已经像这样将UIPickerViewDelegate添加到我的类中:

class ExampleClass: UIViewController, UIPickerViewDelegate

我也创建了一个UIPickerView,并为其设置了代理:

@IBOutlet var year: UIPickerView
year.delegate = self

现在我只是在将以下内容转换为Swift代码方面遇到了麻烦:
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView

非常感谢您的帮助。

2个回答

12

这实际上是 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
使用扩展来实现协议非常好,因为它将与协议相关的所有代码封装在一个地方,如果您将来改变主意,您就知道可以删除哪些代码 :) - Jiaaro
Nate。使用这种方法,我该如何确保我的UIPickerView正在使用? - user3723426
我不确定我是否理解 - 您需要将pickerView添加到视图控制器的视图中,在IB或代码中实现足够的委托方法以为选择器视图提供行内容(可能至少需要“titleForRow,forComponent”方法)。 - Nate Cook
明白了。通常在 titleForRow 方法中,你可以这样做:“return array[row]”,那么在 Swift 中该怎么做呢? - user3723426
就像这样 - 你可能想要在某个地方有一个String[]数组,这样你就可以为每一行返回标题,并返回组件中行数的长度... - Nate Cook
显示剩余2条评论

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接