ios – 在Swift中为UIPickerView委派方法

前端之家收集整理的这篇文章主要介绍了ios – 在Swift中为UIPickerView委派方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
刚开始使用 Swift并且无法调用UIPickerView的委托方法

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

  1. class ExampleClass: UIViewController,UIPickerViewDelegate

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

  1. @IBOutlet var year: UIPickerView
  2. year.delegate = self

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

  1. - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView

任何帮助,将不胜感激

解决方法

这实际上是UIPickerViewDataSource协议中的一个方法,因此您还需要确保设置选择器视图的dataSource属性:year.dataSource = self. Swift本地方式似乎是在类扩展中实现协议,如下所示:
  1. class ExampleClass: UIViewController {
  2. // properties and methods,etc.
  3. }
  4.  
  5. extension ExampleClass: UIPickerViewDataSource {
  6. // two required methods
  7.  
  8. func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int {
  9. return 1
  10. }
  11.  
  12. func pickerView(pickerView: UIPickerView!,numberOfRowsInComponent component: Int) -> Int {
  13. return 5
  14. }
  15. }
  16.  
  17. extension ExampleClass: UIPickerViewDelegate {
  18. // several optional methods:
  19.  
  20. // func pickerView(pickerView: UIPickerView!,widthForComponent component: Int) -> CGFloat
  21.  
  22. // func pickerView(pickerView: UIPickerView!,rowHeightForComponent component: Int) -> CGFloat
  23.  
  24. // func pickerView(pickerView: UIPickerView!,titleForRow row: Int,forComponent component: Int) -> String!
  25.  
  26. // func pickerView(pickerView: UIPickerView!,attributedTitleForRow row: Int,forComponent component: Int) -> NSAttributedString!
  27.  
  28. // func pickerView(pickerView: UIPickerView!,viewForRow row: Int,forComponent component: Int,reusingView view: UIView!) -> UIView!
  29.  
  30. // func pickerView(pickerView: UIPickerView!,didSelectRow row: Int,inComponent component: Int)
  31. }

猜你在找的iOS相关文章