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 navigat开发者_JAVA技巧ion 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.
Or you can use objc_setAssociatedObject and 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 e.g.
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)
}
}
精彩评论