How to tell programmatically if a IBAction has been called by code or by user action
How can I tell programmatically if a IBAction has been called by code or by user action.
Eg
I have a method, -(IBAction)someMethodWithIts:(id)sender
which I have linked to a valueChanged on a UISegmentedControl.
It can be called by,
- User changing segment
- setting the selec开发者_C百科tedIndex in code
- calling
[self someMethodWithIts:foo];
Is there a way to distinguish if the call has come from the first way?
Cheers
Sam
If you can pass nil
as the sender (which is traditional) and use that to indicate it was sent programmatically, that's ok. But anything else I believe is too fragile and you should break up the code like this:
- (void)someMethod {
// stuff shared by everyone
}
- (IBAction)someMethodWithIts:(id)sender {
// stuff specific to IBAction
[self someMethod];
}
If you really want a sender, then you can do it this way:
- (void)someMethodWithIts:(id)sender triggeredByUser:(BOOL)isUser {
}
- (IBAction)someMethodWithIts:(id)sender {
[self someMethodWithIts:sender triggeredByUser:YES];
}
But in general, if you want the IBAction to be different than programatic changes, then don't wire programatic changes to the IBAction.
if ([sender isKindOfClass:[UIControl class]]) {
UIControl *controlSender = (UIControl *)sender;
if (sender.selected) {
// then it's #1
} else {
// then it's #2
}
} else if ([sender isKindOfClass:[Foo class]]) {
// then it's #3
}
Might work. Or poke around other properties of sender defined on UIControl or UISegmentedControl. Maybe state
. My guess is you can find something that's different when the user is interacting vs. when they're not.
You really want to use method like this
-(IBAction)actionWithSender:(id)sender event:(UIEvent*)event
{
if (event) {
} else {
}
}
If you find the event
parameter is nil
, it's from a call in your code, otherwise, the call is from user event.
精彩评论