1

I'm developing the iPhone app. I custom defined the titleview for navigation bar. The title view contains a button, I also defined the delegate method to support the button click event. But when the button clicked, the delegate cannot be executed. I am not sure why ? Below as my codes: 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;
}

In my ViewController, i implement the protocal as below:

MyViewController.h

@interface MyViewController : UIViewController<UPDelegate>

and in the .m file, i wrote the delegate method, but cannot be exeucte. MyViewController.m

-(void)buttonClick{
    NSLog("click title button");
}
jonkroll
  • 15,682
  • 4
  • 50
  • 43
user429079
  • 213
  • 3
  • 8

3 Answers3

2

You have to set your delegate, from you code sample you are creating id<UPDelegate> delegate; in your titleView class.

So in your MyViewController where you have added <UPDelegate>, create an instance of TitleView and set delegate to self.

So in your MyViewController use:

 TitleView*titleView=[[TitleView alloc]init];
 titleView.delegate=self;
iNoob
  • 3,364
  • 2
  • 26
  • 33
  • I already added 'titleView.delegate = self' in my codes, but forgot the parse to the question. And the delegate method still cannot be executed – user429079 Aug 24 '12 at 06:20
  • @user429079 Try adding `-(void)buttonClick;` in your `.h`, and check where command+click on `` takes you in `MyViewController`. And where have you set `delegate=self`? – iNoob Aug 24 '12 at 06:42
1

It sounds like you have not set the value of your titleView's delegate property, so any messages sent to the delegate property are ignored because the delegate is nil.

You should make sure that you are setting your titleView's delegate to be your MyViewController. The best place to do this is most likely in your MyViewController's viewDidLoad: method.

The iOSDev
  • 5,237
  • 7
  • 41
  • 78
jonkroll
  • 15,682
  • 4
  • 50
  • 43
0

Did you set the delegate anywhere? Because you have to set the delegate of your TitleView to MyViewController:

titleView.delegate = self;
NDY
  • 3,527
  • 4
  • 48
  • 63