How to send an object as an argument while listening to UIButton?

I have the following code inside my UIViewController -

[flipButton addTarget:self.navigationController.delegate action:@selector(changeModeAction:) forControlEvents:UIControlEventTouchUpInside];

As you can see, it calls the method inside the delegate of the navigation controller. How to pass an object using this method?

+3
source share
4 answers

Or you can use objc_setAssociatedObject and objc_getAssociatedObject

+2
source

You can use the layer property. Add the object you want to pass as a value in the layer dictionary.

[[btn layer] setValue:yourObj forKey:@"yourKey"];

This one yourObjis available from the button action function:

-(void)btnClicked:(id)sender
{
    yourObj = [[sender layer] valueForKey:@"yourKey"];
}

Using this method, you can pass multiple values ​​to the button function by simply adding new words to the dictionary with different keys.

+8

When changeModeAction:called flipButton, he must convey himself as a sender. If you need additional parameters, you can create a category for the flipButton type to store additional information, or you can configure a dictionary that can be accessed by the navigation manager, for example

if(sender == flipButton)
 id obj = [someDictionary objectForKey:@"flipButtonKey"];
+1
source

extension + Swift 3.0

extension NSObject {

fileprivate struct ObjectTagKeys {
    static var ObjectTag = "ObjectTag"
}

func setObjectTag(_ tag:Any!) {
    objc_setAssociatedObject(self, &ObjectTagKeys.ObjectTag, tag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}

func getObjectTag() -> Any
{
    return objc_getAssociatedObject(self, &ObjectTagKeys.ObjectTag)
}

}
0
source

All Articles