Passing parameters to addTarget:action:forControlEvents
Asked Answered
I

13

129

I am using addTarget:action:forControlEvents like this:

[newsButton addTarget:self
action:@selector(switchToNewsDetails)
forControlEvents:UIControlEventTouchUpInside];

and I would like to pass parameters to my selector "switchToNewsDetails". The only thing I succeed in doing is to pass the (id)sender by writing:

action:@selector(switchToNewsDetails:)

But I am trying to pass variables like integer values. Writing it this way doesn't work :

int i = 0;
[newsButton addTarget:self
action:@selector(switchToNewsDetails:i)
forControlEvents:UIControlEventTouchUpInside];

Writing it this way does not work either:

int i = 0;
[newsButton addTarget:self
action:@selector(switchToNewsDetails:i:)
forControlEvents:UIControlEventTouchUpInside];

Any help would be appreciated :)

Infanta answered 21/10, 2010 at 14:23 Comment(9)
what is the method signature for switchToNewsDetails ?Britnibrito
- (void)switchToNewsDetails:(id)sender; - (void)switchToNewsDetails:(int)i:(id)sender;Infanta
but what that i depends on? is it specific for each button? See my answer - isn't tag property is what you need?Hustle
#26620372Wondrous
@PierreEspenan Your current accepted answer only allows passing integers via tag which is very limiting. I urge you to change it to my answer which allows the passing of ANY object. https://mcmap.net/q/173590/-passing-parameters-to-addtarget-action-forcontroleventsCongener
Plus with the new method you can pass MULTIPLE objects of any kind, as opposed to just one integer. :DCongener
You can use the solution provided in this answer regarding UIButton and passing mulitple parameters to its selector: https://mcmap.net/q/174598/-attach-parameter-to-button-addtarget-action-in-swiftMillstone
You can use the solution provided in this answer regarding UIButton and passing mulitple parameters to its selector: https://mcmap.net/q/174598/-attach-parameter-to-button-addtarget-action-in-swiftMillstone
@LloydKeijzer Interesting indeedInfanta
H
175
action:@selector(switchToNewsDetails:)

You do not pass parameters to switchToNewsDetails: method here. You just create a selector to make button able to call it when certain action occurs (touch up in your case). Controls can use 3 types of selectors to respond to actions, all of them have predefined meaning of their parameters:

  1. with no parameters

    action:@selector(switchToNewsDetails)
    
  2. with 1 parameter indicating the control that sends the message

    action:@selector(switchToNewsDetails:)
    
  3. With 2 parameters indicating the control that sends the message and the event that triggered the message:

    action:@selector(switchToNewsDetails:event:)
    

It is not clear what exactly you try to do, but considering you want to assign a specific details index to each button you can do the following:

  1. set a tag property to each button equal to required index
  2. in switchToNewsDetails: method you can obtain that index and open appropriate deatails:

    - (void)switchToNewsDetails:(UIButton*)sender{
        [self openDetails:sender.tag];
        // Or place opening logic right here
    }
    
Hustle answered 21/10, 2010 at 14:33 Comment(8)
what if we're trying to pass something other than integers? what if I need to pass an object like a string?Iene
@user what's your context? Seems you'll need to pass it separatelyHustle
thanks a lot. where did you find this data? I always appreciate the reference so that maybe I could find it myself next time.Hippogriff
@Hippogriff you can check this link:developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/… for exampleHustle
I get an error trying to use @selector "expected , separator"Wondrous
@quantumpotato, that looks weird. what's your actual code is?Hustle
I need something similar: I need to pass the indexpath.row AND the indexpath.section to be passed. How to achieve this?Laband
You don't need to pass it separately. If you are passing any NSObject you can just say [button.layer setValue:yourObject forKey:@"anyKey"]; and then in the method just check (objectClass *)[button.layer valueForKey:@"anyKey"]; It's like a more free version of .tagCongener
L
64

To pass custom params along with the button click you just need to SUBCLASS UIButton.

(ASR is on, so there's no releases in the code.)

This is myButton.h

#import <UIKit/UIKit.h>

@interface myButton : UIButton {
    id userData;
}

@property (nonatomic, readwrite, retain) id userData;

@end

This is myButton.m

#import "myButton.h"
@implementation myButton
@synthesize userData;
@end

Usage:

myButton *bt = [myButton buttonWithType:UIButtonTypeCustom];
[bt setFrame:CGRectMake(0,0, 100, 100)];
[bt setExclusiveTouch:NO];
[bt setUserData:**(insert user data here)**];

[bt addTarget:self action:@selector(touchUpHandler:) forControlEvents:UIControlEventTouchUpInside];

[view addSubview:bt];

Recieving function:

- (void) touchUpHandler:(myButton *)sender {
    id userData = sender.userData;
}

If you need me to be more specific on any part of the above code — feel free to ask about it in comments.

Liturgical answered 25/1, 2013 at 18:24 Comment(6)
I think this is the best wayHarkness
Most elegant solution.Forde
Great answer...very customizable. Exactly what I was looking for. MOLODETS! :)Eventempered
thanks for the feedback :) Glad, that it is useful for somebody :)Liturgical
I have a button needed to customize in xib file. How can I make this button as mybutton programmatically?Chick
Simple and useful workaround. Just let me add that this is similar to the tag property in Android views. They can store any object. And you can also store objects by key like in a Dictionary/Map.Merrileemerrili
C
21

Need more than just an (int) via .tag? Use KVC!

You can pass any data you want through the button object itself (by accessing CALayers keyValue dict).


Set your target like this (with the ":")

[myButton addTarget:self action:@selector(buttonTap:) forControlEvents:UIControlEventTouchUpInside];

Add your data(s) to the button itself (well the .layer of the button that is) like this:

NSString *dataIWantToPass = @"this is my data";//can be anything, doesn't have to be NSString
[myButton.layer setValue:dataIWantToPass forKey:@"anyKey"];//you can set as many of these as you'd like too!

*Note: The key shouldn't be a default key of a CALayer property, consider adding a unique prefix to all of your keys to avoid any issues arising from key collision.


Then when the button is tapped you can check it like this:

-(void)buttonTap:(UIButton*)sender{

    NSString *dataThatWasPassed = (NSString *)[sender.layer valueForKey:@"anyKey"];
    NSLog(@"My passed-thru data was: %@", dataThatWasPassed);

}
Congener answered 14/10, 2016 at 20:43 Comment(8)
there is no method in UIButton.layer to set or add an object. Where do you get that solution ?Inartistic
A UIButton is a type of UIView, all UIViews have CALayer .layer property. CALayer contains NSDictionary behaviors. Note this is Objective-C not Swift, that may be the issue? Here are Apple's Docs on CALayer key-value coding: developer.apple.com/library/content/documentation/Cocoa/…Congener
I am doing in Objective-C only, but when u try to write addObject for UIButton compiler says no method for UIbutton. Have tried to do it in Xcode ?Inartistic
@Inartistic My apologies, it's setValue: not addObject:. Correcting my code above nowCongener
That's fine, I did the other way but I liked your answer better than others in this post. +1Inartistic
This should be the answer on top. By far the easiest way to do it!. thanks!Lanthanide
It should be accepted answer.Its much easier and smart way.Anthracnose
Great answer! Wish I'd known this a long time ago.Hanshansard
P
19

Target-Action allows three different forms of action selector:

- (void)action
- (void)action:(id)sender
- (void)action:(id)sender forEvent:(UIEvent *)event
Prud answered 21/10, 2010 at 14:33 Comment(0)
S
8

I made a solution based in part by the information above. I just set the titlelabel.text to the string I want to pass, and set the titlelabel.hidden = YES

Like this :

UIButton *imageclick = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
imageclick.frame = photoframe;
imageclick.titleLabel.text = [NSString stringWithFormat:@"%@.%@", ti.mediaImage, ti.mediaExtension];
imageclick.titleLabel.hidden = YES;

This way, there is no need for a inheritance or category and there is no memory leak

Scevor answered 29/10, 2013 at 20:41 Comment(0)
T
5

I was creating several buttons for each phone number in an array so each button needed a different phone number to call. I used the setTag function as I was creating several buttons within a for loop:

for (NSInteger i = 0; i < _phoneNumbers.count; i++) {

    UIButton *phoneButton = [[UIButton alloc] initWithFrame:someFrame];
    [phoneButton setTitle:_phoneNumbers[i] forState:UIControlStateNormal];

    [phoneButton setTag:i];

    [phoneButton addTarget:self
                    action:@selector(call:)
          forControlEvents:UIControlEventTouchUpInside];
}

Then in my call: method I used the same for loop and an if statement to pick the correct phone number:

- (void)call:(UIButton *)sender
{
    for (NSInteger i = 0; i < _phoneNumbers.count; i++) {
        if (sender.tag == i) {
            NSString *callString = [NSString stringWithFormat:@"telprompt://%@", _phoneNumbers[i]];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callString]];
        }
    }
}
Tina answered 25/2, 2014 at 10:26 Comment(1)
you can improve this code: - (void)call:(UIButton *)sender { NSString *phoneNumber = _phoneNumbers[i]; NSString *callString = [NSString stringWithFormat:@"telprompt://%@", phoneNumber]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callString]]; }Kovacev
I
2

As there are many ways mentioned here for the solution, Except category feature .

Use the category feature to extend defined(built-in) element into your customisable element.

For instance(ex) :

@interface UIButton (myData)

@property (strong, nonatomic) id btnData;

@end

in the your view Controller.m

 #import "UIButton+myAppLists.h"

UIButton *myButton = // btn intialisation....
 [myButton set btnData:@"my own Data"];
[myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

Event handler:

-(void)buttonClicked : (UIButton*)sender{
    NSLog(@"my Data %@", sender. btnData);
}
Icaria answered 13/10, 2014 at 9:40 Comment(1)
You can't really add properties in categories.Zemstvo
G
2

You can replace target-action with a closure (block in Objective-C) by adding a helper closure wrapper (ClosureSleeve) and adding it as an associated object to the control so it gets retained. That way you can pass any parameters.

Swift 3

class ClosureSleeve {
    let closure: () -> ()

    init(attachTo: AnyObject, closure: @escaping () -> ()) {
        self.closure = closure
        objc_setAssociatedObject(attachTo, "[\(arc4random())]", self, .OBJC_ASSOCIATION_RETAIN)
    }

    @objc func invoke() {
        closure()
    }
}

extension UIControl {
    func addAction(for controlEvents: UIControlEvents, action: @escaping () -> ()) {
        let sleeve = ClosureSleeve(attachTo: self, closure: action)
        addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
    }
}

Usage:

button.addAction(for: .touchUpInside) {
    self.switchToNewsDetails(parameter: i)
}
Geanticline answered 5/7, 2017 at 5:12 Comment(2)
Above method ( self.switchToNewsDetails(parameter: i)) firing 2 times , why help me outHynes
The code works for me. Tested in a new Single View App project pastebin.com/tPaqetMb. So the problem is probably in your code, like calling button.addAction() twice. Add a breakpoint to button.addAction and also on the first line inside the closure and try to debug it yourself.Pfister
J
2

There is another one way, in which you can get indexPath of the cell where your button was pressed:

using usual action selector like:

 UIButton *btn = ....;
    [btn addTarget:self action:@selector(yourFunction:) forControlEvents:UIControlEventTouchUpInside];

and then in in yourFunction:

   - (void) yourFunction:(id)sender {

    UIButton *button = sender;
    CGPoint center = button.center;
    CGPoint rootViewPoint = [button.superview convertPoint:center toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:rootViewPoint];
    //the rest of your code goes here
    ..
}

since you get an indexPath it becames much simplier.

Jacksonjacksonville answered 2/4, 2018 at 15:17 Comment(0)
B
1

See my comment above, and I believe you have to use NSInvocation when there is more than one parameter

more information on NSInvocation here

http://cocoawithlove.com/2008/03/construct-nsinvocation-for-any-message.html

Britnibrito answered 21/10, 2010 at 14:27 Comment(2)
Actually, I don't want to pass several params, I just want an integer.Infanta
actually there's performSelector:withObject:withObject: method that allow to call selectors with 2 parameters. But for more you need NSInvocationHustle
T
1

This fixed my problem but it crashed unless I changed

action:@selector(switchToNewsDetails:event:)                 

to

action:@selector(switchToNewsDetails: forEvent:)              
Thermy answered 12/2, 2011 at 14:2 Comment(0)
N
0

I subclassed UIButton in CustomButton and I add a property where I store my data. So I call method: (CustomButton*) sender and in the method I only read my data sender.myproperty.

Example CustomButton:

@interface CustomButton : UIButton
@property(nonatomic, retain) NSString *textShare;
@end

Method action:

+ (void) share: (CustomButton*) sender
{
    NSString *text = sender.textShare;
    //your work…
}

Assign action

    CustomButton *btn = [[CustomButton alloc] initWithFrame: CGRectMake(margin, margin, 60, 60)];
    // other setup…

    btnWa.textShare = @"my text";
    [btn addTarget: self action: @selector(shareWhatsapp:)  forControlEvents: UIControlEventTouchUpInside];
Newfangled answered 24/5, 2016 at 0:49 Comment(0)
I
0

If you just want to change the text for the leftBarButtonItem shown by the navigation controller together with the new view, you may change the title of the current view just before calling pushViewController to the wanted text and restore it in the viewHasDisappered callback for future showings of the current view.

This approach keeps the functionality (popViewController) and the appearance of the shown arrow intact.

It works for us at least with iOS 12, built with Xcode 10.1 ...

Insolate answered 11/12, 2018 at 20:35 Comment(1)
I don't think this reply is related to the question.Infanta

© 2022 - 2024 — McMap. All rights reserved.