为动态创建的 UIPickerView 添加协议
Adding protocols for dynamically created UIPickerView
这个问题与SO question (please see accepted answer)有关。我正在将 UIPickerView 添加到未在其视图中添加 UIPickerViewDelegate 或 UIPickerViewDataSource 协议的视图界面。但是,UIPickerView 对象所需的所有方法都已正确实现,程序在这些委托下运行良好:
pv.delegate = self;
pv.dataSource = self;
由于class接口中没有添加协议,Xcode相应地抛出这两个警告:
Assigning to 'id<UIPickerViewDelegate>' from incompatible type
Assigning to 'id<UIPickerViewDataSource>' from incompatible type
此代码似乎添加了所需的协议,并且一旦为选取器视图委托和数据源属性分配了新创建的 delegateClass,警告就会停止。
UIPickerView *pv = [[UIPickerView alloc] initWithFrame:CGRectMake(x, y, width, height)];
Class<UIPickerViewDelegate, UIPickerViewDataSource> delegatedClass = (Class<UIPickerViewDelegate, UIPickerViewDataSource>)[self class];
pv.delegate = delegatedClass;
pv.dataSource = delegatedClass;
但是,即使没有错误,程序也会崩溃。
执行或分配是否有误?
更新: 错误截图
您正在尝试将 class 设置为委托人。请设置一个实例来解决此问题。
UIPickerView *pv = [[UIPickerView alloc] initWithFrame:CGRectMake(x, y, width, height)];
pv.delegate = self;
而不是
UIPickerView *pv = [[UIPickerView alloc] initWithFrame:CGRectMake(x, y, width, height)];
Class<UIPickerViewDelegate, UIPickerViewDataSource> delegatedClass = (Class<UIPickerViewDelegate, UIPickerViewDataSource>)[self class];
pv.delegate = delegatedClass;
在定义您的自定义委托协议时仅使用
@property(nonatomic,assign)id delegate;
而不是
@property(nonatomic,assign)id<YOUR_PROTOCOL> delegate;
这个问题与SO question (please see accepted answer)有关。我正在将 UIPickerView 添加到未在其视图中添加 UIPickerViewDelegate 或 UIPickerViewDataSource 协议的视图界面。但是,UIPickerView 对象所需的所有方法都已正确实现,程序在这些委托下运行良好:
pv.delegate = self;
pv.dataSource = self;
由于class接口中没有添加协议,Xcode相应地抛出这两个警告:
Assigning to 'id<UIPickerViewDelegate>' from incompatible type
Assigning to 'id<UIPickerViewDataSource>' from incompatible type
此代码似乎添加了所需的协议,并且一旦为选取器视图委托和数据源属性分配了新创建的 delegateClass,警告就会停止。
UIPickerView *pv = [[UIPickerView alloc] initWithFrame:CGRectMake(x, y, width, height)];
Class<UIPickerViewDelegate, UIPickerViewDataSource> delegatedClass = (Class<UIPickerViewDelegate, UIPickerViewDataSource>)[self class];
pv.delegate = delegatedClass;
pv.dataSource = delegatedClass;
但是,即使没有错误,程序也会崩溃。
执行或分配是否有误?
更新: 错误截图
您正在尝试将 class 设置为委托人。请设置一个实例来解决此问题。
UIPickerView *pv = [[UIPickerView alloc] initWithFrame:CGRectMake(x, y, width, height)];
pv.delegate = self;
而不是
UIPickerView *pv = [[UIPickerView alloc] initWithFrame:CGRectMake(x, y, width, height)];
Class<UIPickerViewDelegate, UIPickerViewDataSource> delegatedClass = (Class<UIPickerViewDelegate, UIPickerViewDataSource>)[self class];
pv.delegate = delegatedClass;
在定义您的自定义委托协议时仅使用
@property(nonatomic,assign)id delegate;
而不是
@property(nonatomic,assign)id<YOUR_PROTOCOL> delegate;