如何为UIView子类创建自定义委托协议?

时间:2010-04-19 18:07:03

标签: iphone uiview delegates protocols nsobject

我正在制作一些标签,我想为他们创建自己的委托但是当我尝试向委托发送动作时没有任何反应。

我也尝试过这个教程: link text

但它对我不起作用:(

这是我的代码: TiMTabBar.h

    @protocol TiMTabBarDelegate;

@interface TiMTabBar : UIView {
    id<TiMTabBarDelegate>  __delegate;

    ...

    int selectedItem;

    ...
}
//- (id)init;
- (id)initWithDelegate:(id)aDelegate;

- (void)setSelectedIndex:(int)item;
..

@property (nonatomic) int selectedItem;
@property(assign) id <TiMTabBarDelegate> __delegate; 
..


...

@end

@protocol TiMTabBarDelegate<NSObject>
//@optional

- (void)tabBar:(TiMTabBar *)_tabBar didSelectIndex:(int)index;

@end

TiMTabBar.m:

#import "TiMTabBar.h"

...

@interface NSObject (TiMTabBarDelegate)
- (void)tabBar:(TiMTabBar *)_tabBar didSelectIndex:(int)index;
@end

@implementation TiMTabBar

@synthesize selectedItem;
@synthesize __delegate;
...

/*
- (id)init
{
    ...

    return self;
}
 */

- (id)initWithDelegate:(id)aDelegate;
{
    //[super init];
    __delegate = aDelegate;
    return self;
}

- (void)awakeFromNib
{
    //[self init];
    //[self initWithDelegate:self];
    ...
}

- (void)setSelectedIndex:(int)item {
    selectedItem = item;
    if (self.__delegate != NULL && [self.__delegate respondsToSelector:@selector(tabBar:didSelectIndex:)]) {
        [__delegate tabBar:self didSelectIndex:selectedItem];
    } 

    ...
    if (item == 0) {
        ...
    } else if (item == 1) {
        ...
    } else if (item == 2) {
        ...
    } else if (item == 3) {
        ...
    } else if (item == 4) {
        ...
    } else {
        ...
    }
}

/*
- (void)tabBar:(TiMTabBar *)_tabBar didSelectIndex:(int)index;
{
    //[delegate tabBar:self didSelectIndex:index];
    //if (self.delegate != NULL && [self.delegate respondsToSelector:@selector(tabBar:didSelectIndex:)]) {
        //[delegate tabBar:self didSelectIndex:selectedItem];
    //}
    NSLog(@"tabBarDelegate: %d",index);
}
 */


@end

委托仅在本身内部工作,而不在任何其他文件中起作用,如:

@interface XXXController : UIViewController <TiMTabBarDelegate> {
    ...

    ...

    IBOutlet TiMTabBar *tabBar;
    ...
}
...

@end

XXXController.m:

#import "XXXController.h"
#import <QuartzCore/QuartzCore.h>

@implementation XXXController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self becomeFirstResponder];
    ...
    tabBar = [[TiMTabBar alloc] initWithDelegate:self];
    //tabBar.__delegate = self;
    ...
}

#pragma mark TiMTabBar Stuff

- (void)tabBar:(TiMTabBar *)_tabBar didSelectIndex:(int)index;
{
    NSLog(@"Controller/tabBarDelegate: %d",index);
}

@end

这些似乎都不适用于XXXController。任何人都知道如何使这项工作?

2 个答案:

答案 0 :(得分:1)

看起来 - 在awakeFromNib中,您将委托设置为自身。因此,每当您尝试发送委托消息时,您实际上是将它们发送到您的TiMTabBar实例,而不是XXXController。

答案 1 :(得分:1)

在你的XXXController viewDidLoad之后,在分配并初始化一个新的TiMTabBar后,你是否将它添加到控制器的视图中?如果没有,可能您点击的视图中的标签栏是从没有设置委托的笔尖加载的标签栏。