【问题标题】:Why my iPhone app cannot call the delegate method为什么我的 iPhone 应用程序无法调用委托方法
【发布时间】:2012-08-23 05:35:22
【问题描述】:

我正在开发 iPhone 应用程序。我自定义了导航栏的标题视图。标题视图包含一个按钮,我还定义了委托方法来支持按钮单击事件。但是当点击按钮时,委托不能被执行。我不知道为什么? 下面作为我的代码: UPDelegate.h

@protocol UPDelegate <NSObject>
@optional
-(void)buttonClick;
@end

TitleView.h

#import <UIKit/UIKit.h>
#import "UPDelegate.h"
@interface TitleView :UIView
@property (nonatomic, unsafe_unretained) id<UPDelegate> delegate;
-(id)initWithCustomTitleView;
@end

TitleView.m

@synthesize delegate;
-(id)initWithCustomTitleView
{
    self = [super init];
    if (self) {
        UIButton *titleButton = [UIButton buttonWithType:UIBUttonTypeCustom];
        titleButton.frame = CGRectMake(0, 0, 20, 44);
        [titleButton setTitle:@"ABC" forState:UIControlStateNormal];

        // add action
        [titleButton addTarget:delegate action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:titleButton];
    }
    return self;
}

在我的 ViewController 中,我实现了如下协议:

MyViewController.h

@interface MyViewController : UIViewController<UPDelegate>

在.m 文件中,我编写了委托方法,但无法执行。 MyViewController.m

-(void)buttonClick{
    NSLog("click title button");
}

【问题讨论】:

  • 你在哪里设置代理?
  • 你在哪里将代理“设置”到你的 MyViewController?

标签: iphone ios navigationbar titleview


【解决方案1】:

您必须设置您的delegate,从您在titleView 类中创建id&lt;UPDelegate&gt; delegate; 的代码示例。

因此,在您添加了&lt;UPDelegate&gt;MyViewController 中,创建TitleView 的实例并将委托设置为self。

所以在你的MyViewController 中使用:

 TitleView*titleView=[[TitleView alloc]init];
 titleView.delegate=self;

【讨论】:

  • 我已经在我的代码中添加了“titleView.delegate = self”,但忘记了对问题的解析。并且委托方法仍然无法执行
  • @user429079 尝试在您的.h 中添加-(void)buttonClick;,并检查命令+单击&lt;UPDelegate&gt; 会将您带到MyViewController 的位置。你在哪里设置delegate=self
【解决方案2】:

听起来您还没有设置 titleView 的委托属性的值,因此发送到委托属性的任何消息都将被忽略,因为委托为 nil。

您应该确保将 titleView 的委托设置为您的 MyViewController。执行此操作的最佳位置很可能在 MyViewController 的 viewDidLoad: 方法中。

【讨论】:

    【解决方案3】:

    您是否在任何地方设置了委托?因为您必须将 TitleView 的委托设置为 MyViewController:

    titleView.delegate = self;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多