gpt4 book ai didi

ios - 为动态创建的 UIPickerView 添加协议(protocol)

转载 作者:行者123 更新时间:2023-11-29 02:00:00 25 4
gpt4 key购买 nike

这个问题与此相关SO question (please see accepted answer) 。我将 UIPickerView 添加到未在其界面中添加 UIPickerViewDelegateUIPickerViewDataSource 协议(protocol)的 View 。但是,UIPickerView 对象所需的所有方法都已正确实现,并且程序使用这些委托(delegate)运行良好:

pv.delegate = self;
pv.dataSource = self;

由于类接口(interface)中没有添加协议(protocol),因此 Xcode 会相应地抛出这两个警告:

Assigning to 'id<UIPickerViewDelegate>' from incompatible type
Assigning to 'id<UIPickerViewDataSource>' from incompatible type

此代码似乎添加了所需的协议(protocol),并且一旦为选取器 View 委托(delegate)和数据源属性分配了新创建的委托(delegate)类,警告就会停止。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;

但是,即使没有错误,程序也会崩溃。

也许是实现或分配错误?

更新: 错误的屏幕截图

enter image description here

最佳答案

您正在尝试将一个类设置为委托(delegate)。请设置一个实例来解决此问题。

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;

在定义您的自定义委托(delegate)协议(protocol)时仅使用

@property(nonatomic,assign)id delegate;

代替

@property(nonatomic,assign)id<YOUR_PROTOCOL> delegate;

关于ios - 为动态创建的 UIPickerView 添加协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30478174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com