Adding Context to a User Interface Control or NSObject

It’s good that addTarget on UIButton . I only wish that I could hide the state in UIButton, so that when I call the target method, I could magically pull this state (any identifier) ​​from the sender.

Sort of:

 [button shoveMyObjectInThere:foo]; [button addTarget:self action:@selector(touchyTouchy:) forControlEvents:UIControlEventTouchUpInside]; 

The following are:

 -(void) touchyTouchy:(id) sender { UIButton button = (UIButton*)sender; id foo = [button getByObjectBack]; // do something interesting with foo } 

It would be great if UIButton had an id context property in which developers could load things, but that doesn't seem to be the case. Objective-C is a very dynamic language, though, so I wonder if there is any sneaky way I can add to an object at runtime?

+4
source share
4 answers

You can try to create an associative link.

 #import <objc/runtime.h> objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy); objc_getAssociatedObject(id object, void *key); 
+5
source

Something like setValue:forKey: part of the Objective-C key value encoding function?

0
source

So, I just did a quick test and found interesting results.

 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button setTitle:@"Hello" forState:UIControlStateNormal]; [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; button.frame = CGRectMake(100, 100, 100, 100); [self.window addSubview:button]; // ... - (void)buttonClicked:(id)sender { NSLog(@"button clicked %@", [sender class]); } 

Fingerprints: button clicked UIRoundedRectButton

So it seems that this should be possible ... In truth, I ran into some UIButton subclassing UIButton to get a complete example of work, but that seems promising. :)

0
source

The official solution is to use the "tag" property:

 [self.someMutableArray addObject:foo]; button.tag = self.someMutableArray.count - 1; [button addTarget:self action:@selector(touchyTouchy:) forControlEvents:UIControlEventTouchUpInside]; 

Then:

 -(void) touchyTouchy:(id) sender { UIButton button = (UIButton*)sender; id foo = self.someMutableArray[button.tag]; // do something interesting with foo } 

In most situations, you would use enum or a constant for the tag, but the array is obviously more flexible.

0
source

Source: https://habr.com/ru/post/1334441/


All Articles