Passing parameters to addTarget:action:forControlEvents

IosObjective CIphoneCocoa TouchUicontrolevents

Ios Problem Overview


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 :)

Ios Solutions


Solution 1 - Ios

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
    }
    

Solution 2 - Ios

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.

Solution 3 - Ios

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);

}

Solution 4 - Ios

Target-Action allows three different forms of action selector:

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

Solution 5 - Ios

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

Solution 6 - Ios

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]];
        }
    }
}

Solution 7 - Ios

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);
}

 

Solution 8 - Ios

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)
}

Solution 9 - Ios

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.

Solution 10 - Ios

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

Solution 11 - Ios

This fixed my problem but it crashed unless I changed

action:@selector(switchToNewsDetails:event:)                 

to

action:@selector(switchToNewsDetails: forEvent:)              

Solution 12 - Ios

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];

Solution 13 - Ios

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 ...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPierre EspenanView Question on Stackoverflow
Solution 1 - IosVladimirView Answer on Stackoverflow
Solution 2 - IosYuriy PolezhayevView Answer on Stackoverflow
Solution 3 - IosAlbert RenshawView Answer on Stackoverflow
Solution 4 - IosBenoîtView Answer on Stackoverflow
Solution 5 - IosAbhinav SinghView Answer on Stackoverflow
Solution 6 - Iosrjdunwoody91View Answer on Stackoverflow
Solution 7 - IosKumar KLView Answer on Stackoverflow
Solution 8 - IosMarián ČernýView Answer on Stackoverflow
Solution 9 - IosAnton LisitsynView Answer on Stackoverflow
Solution 10 - IosAaron SaundersView Answer on Stackoverflow
Solution 11 - IosiphaawView Answer on Stackoverflow
Solution 12 - IosiNiko84View Answer on Stackoverflow
Solution 13 - IosBubuView Answer on Stackoverflow