【问题标题】:Defining a delegate in a UIView/UIViewController relationship在 UIView/UIViewController 关系中定义委托
【发布时间】:2014-03-05 15:46:38
【问题描述】:

我有一个名为 TargetView 的子类 UIView,它包含在名为 MainViewController 的 UIViewController 中。我想将 MainViewController 设置为 TargetView 的委托,以便 MainViewController 可以接收来自子视图(TargetView)的消息。

在我的 MainViewController (UIViewController) 标题中,我有以下内容:

#import <UIKit/UIKit.h>
#import "TargetView.h"

@class TargetView;

@interface MainViewController : UIViewController <TargetViewDelegate>

@property (strong, nonatomic) IBOutlet TargetView *target;    
@property (strong, nonatomic) IBOutlet UILabel *lblResults;

@end

当我在接口声明中设置 TargetViewDelegate 时,它​​会显示在代码完成中,因此它知道它在那里,但随后构建失败并显示消息:找不到协议声明..."

在我的 TargetView (UIView) 类中,我有以下内容:

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "MainViewController.h"

@protocol TargetViewDelegate

@required
-(void)receivedTargetTap;

@end

@interface TargetView : UIView{

    id<TargetViewDelegate> delegate;
}

@property (nonatomic,strong) NSString *lblResults;
@property (nonatomic,weak) id<TargetViewDelegate> delegate;

@end

创建自定义代表对我来说是未知领域。谁能告诉我我做错了什么?谢谢!

【问题讨论】:

  • 您可以尝试使用以下命令更改您的@protocol:@protocol TargetViewDelegate 吗?
  • 我将发布一个答案,并对您的代码进行一些修改。
  • 需要在del的声明后加上

标签: ios objective-c delegates


【解决方案1】:

我相信您的 TargetView.h 应该是:

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

@protocol TargetViewDelegate <NSObject>

@required
-(void)receivedTargetTap;

@end

@interface TargetView : UIView

@property (nonatomic, strong) NSString *lblResults;
@property (nonatomic, weak) id<TargetViewDelegate> delegate;

@end

MainViewController.h:

#import <UIKit/UIKit.h>
#import "TargetView.h"

@interface MainViewController : UIViewController <TargetViewDelegate>

@property (strong, nonatomic) IBOutlet TargetView *target;    
@property (strong, nonatomic) IBOutlet UILabel *lblResults;

@end

在您的代码中,您必须在协议定义后添加 &lt;NSObject&gt;,并删除 TargetView 类中的 MainViewController.h 导入。

【讨论】:

  • 仍然得到相同的消息:找不到 TargetViewController 的协议声明
  • 您说的是“TargetViewController”,但您的代码中没有这样的 TargetViewController。
  • 对不起,我的意思是 TargetViewDelegate
  • @Pheepster :我刚刚尝试了我在一个空白项目中发布的完整代码,它可以工作。正如 Romain 所说,这可能是因为您尝试在 TargetView 中 #import "MainViewController.h"。你能重试这段代码吗?
【解决方案2】:

我认为您在两个.h 文件中的import 语句可能存在问题。

为什么从TargetView.h 引用MainViewController.h?好像你不需要它。另一方面,你应该去掉MainViewController.h@class TargetView的前向声明,简单的#import "TargetView.h"就足够了。

之后,您还需要实现所需的- (void)receivedTargetTap;,否则编译器会再次抱怨TargetViewDelegate 没有完全实现。

【讨论】:

  • 你是对的,似乎是 MainViewController.h 导入导致了问题。
猜你喜欢
  • 1970-01-01
  • 2017-01-17
  • 2016-11-03
  • 1970-01-01
  • 2017-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多