简体   繁体   中英

How to send an object as argument when a UIButton is tapped?

I have the following code inside my UIViewController -

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

As you can see, it calls a method inside it's navigation controller delegate. How do I correctly pass along an object to this method?

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

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

This yourObj is accessible from the button action function:

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

With this method you can pass multiple values to the button function just by adding new objects in the dictionary with different keys.

或者您可以使用objc_setAssociatedObject和objc_getAssociatedObject

When changeModeAction: is called flipButton should pass itself as the sender. If you need additional parameters passed you could create a category for the type of flipButton to store additional information or you could set up a dictionary that the navigationController can access eg

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM