开发者

Selectors with arguments in Obj-C

So basically I have a big list of buttons that's present dropdowns and other things, and these buttons are created dynamically. So to capture the value for the appropriate button's data, I need to set it's action selector to a function that takes 1 extra parameter.

For example, using this selector on t开发者_如何学JAVAhis dropdown, with the method below, returns an error that the selector is unrecognized. How can I get the selector to recognize the parameter I'm passing in? (In this case the variable 'name')

The apple docs at: http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocSelectors.html#//apple_ref/doc/uid/TP30001163-CH23-SW1

On the last paragraph in the header 'The Target-Action Design Pattern', the Apple Docs imply that this can be done, but do not give an example of using a custom message, or maybe I'm just misunderstanding?

SEL sel = @selector(openDropdown:name:);
[dropdownSelector addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];


-(void) openDropdown: (NSString *) anotherArg : (id) sender {
 // Stuff here based on anotherArg
}


You should be able to derive the clicked button's information from the id input arg

    UIButton *button = (UIButton *) sender
     NSString *title = [button currentTitle];

No need to pass the extra param


What you're asking can't be done. From the docs:

UIKit allows three different forms of action selector:

- (void)action
- (void)action:(id)sender
- (void)action:(id)sender forEvent:(UIEvent *)event

Since you have no influence on the event parameter, the sender object must include all information you want to pass to the action method.

Despite what you have written in your comment on mihirsm's answer, you can indeed subclass UIButton to add all the additional info you want to each button instance. You could also use the button's tag property to identify it (assign a unique tag to each button) and store all the additional info in an array or dictionary using the tags as keys.

Update: In the future, you can also use associative storage to add data to objects without subclassing them but this technology is not (yet) available on the iPhone platform (10.6 only at the moment).


CALayers support arbitrary keys for key-value coding; you can use this to attach arbitrary layers:

[[button1 layer] setValue:@"firstButtonData" forKey:@"myKey"];
[[button2 layer] setValue:@"secondButtonData" forKey:@"myKey"];

And later:

- (void)action:(id)sender forEvent:(UIEvent *)event
{
    NSLog(@"Data for the button that was pressed: %@", [[sender layer] valueForKey:@"myKey"]);
}

Be careful not to collide with any of the existing properties on CALayer

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜