Type “myViewController” does not conform to protocol UIPIckerDataSource in Swift

£可爱£侵袭症+ 提交于 2019-11-27 20:27:20

问题


I just create a new class in Swift, it's called myViewController and it's a UIViewController. Now I'm trying to make it a UIPickerViewDelegate and DataSource but i got a strange error

import UIKit

class myViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
   ...
}

It says Type "myViewController" does not conform to protocol UIPIckerDataSource over the UIPickerViewDataSource.

Is it a bug of Xcode-Beta 3??


回答1:


You need to implement all the required methods of UIPickerViewDataSource and UIPickerViewDelegate, if you want to conform to these protocols.

Swift is more like java when it comes to protocols because if you don't implement all the required methods declared by a protocol you are going to get a compile time error instead of a run time exception.




回答2:


Fix-it in XCode 8.1 inserts a deprecated version of the method below if you're using Swift 3:

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return componentNumber
}

In XCode 10.0+

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return componentNumber
}



回答3:


Implement required method of UIPickerDataSource as in documentation.

The data source provides the picker view with the number of components, and the number of rows in each component, for displaying the picker view data. Both methods in this protocol are required.

So you need to implement these methods

func numberOfComponentsInPickerView(_ pickerView: UIPickerView!) -> Int {}

   func pickerView(_ pickerView: UIPickerView!,
numberOfRowsInComponent component: Int) -> Int{}



回答4:


My problem was that I had override in front of the implementation function, where Swift doesn't consider protocol method implementations to be overrides (same). Just taking out the override keyword fixed the issue.




回答5:


My problem is protocol's method name is illegal,

@protocol ContactsSelectDelegate <NSObject>

- (void)selectContacts:(NSMutableArray *)contacts Tags:(NSMutableArray *)tags;

@end

Here, Tags: should be tags:.
I hope my answer is helpful.



来源:https://stackoverflow.com/questions/24970877/type-myviewcontroller-does-not-conform-to-protocol-uipickerdatasource-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!