1

我正在寻找一个具有类似于 UIButton 工作方式的“事件列表”的类,您可以在其中添加多个目标和选择器。

编写一个很容易,但如果 Apple 已经提供了解决方案,我宁愿使用它也不愿维护更多代码。

笔记:

这是一个非可视类,所以我真的不想使用任何 UI 特定的东西。

编辑:

我最终使用堆叠的 NSDictionary 实例滚动了我自己的基本事件调度程序类型类。

@implementation ControllerBase
@synthesize eventHandlers;


- (id) init
{
    self = [super init];

    if (self!=NULL)
    {
        NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
        [self setEventHandlers: dict];

        [dict release];
    }

    return self;
}


-(void) addTarget: (id) target  action:(SEL) selector  forEvent:(NSString*) eventName
{
    NSString* selectorString =  NSStringFromSelector(selector);   
    NSMutableDictionary* eventDictionary = [eventHandlers objectForKey:eventName];

    if (eventDictionary==NULL)
    {
        eventDictionary = [[NSMutableDictionary alloc] init];
        [eventHandlers setValue:eventDictionary forKey:eventName];
    }

    NSArray* array = [NSArray arrayWithObjects:selectorString,target, nil];
    [eventDictionary setValue:array forKey: [target description]];
}

-(void) removeTarget: (id) target  action:(SEL) selector  forEvent:(NSString*) eventName;
{
    NSMutableDictionary* eventDictionary = [eventHandlers objectForKey:eventName];

    //must have already been removed
    if (eventDictionary!=NULL)
    {
        //remove event
        [eventDictionary removeObjectForKey:target];

        //remove sub dictionary
        if ([eventDictionary count]==0)
        {
            [eventHandlers removeObjectForKey:eventName];
            [eventDictionary release];
        }
    }


}

-(void) fireEvent:(NSString *)eventName
{
     NSMutableDictionary* eventDictionary = (NSMutableDictionary*) [eventHandlers objectForKey:eventName];

    if (eventDictionary!=NULL)
    {
        for(id key in eventDictionary)
        {
            NSArray* eventPair= [eventDictionary valueForKey:key];

            if (eventPair!=NULL)
            {

                NSString* selectorString = (NSString*)[eventPair objectAtIndex:0];

                //remove colon at end
                SEL selector = NSSelectorFromString ( [selectorString substringWithRange: NSMakeRange(0, [selectorString length]-1)] ) ;
                id target = [eventPair objectAtIndex:1];

                [target performSelector:selector];
            }

        }
    }

}

-(void) dealloc
{
    for(id key in eventHandlers) 
    {
        NSMutableDictionary* eventDictionary = (NSMutableDictionary*) [eventHandlers objectForKey:key];

        for(id key in eventDictionary)
        {
            [eventDictionary removeObjectForKey:key];
        }

        [eventDictionary release];

    }

    [eventHandlers release];
    [super dealloc];
}



@end
4

1 回答 1

5

UIButton是 的子类UIControlUIControl管理每个控制事件的目标/动作列表。它有一组预定义的控制事件,例如UIControlEventTouchUpInsideUIControlEventValueChanged。每个控制事件都由掩码中的一个位表示。UIControlEventApplicationReserved = 0x0F000000位掩码有四位为应用程序定义的事件 ( )保留。

如果UIControl没有做您想做的事,您将需要推出自己的事件管理。

于 2012-07-22T19:36:59.460 回答