Am I allowed to have one button with two actions in one for-loop?
Is there any reason I shouldn't do this? I'm fairly new at programming iPhone so I just want to check that its not making my memory footprint really high for some reason or anything like that.
I'm creating buttons in a loop (one for each letter in a phrase) and then there may be up to about 100 instances of this code running simultaneously so if there's a problem with it it could be a big problem.
Thanks for the advice!
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton setTag:l];
CGRect buttonRect = CGRectMake(11+charact*20, -40 + line*50, 18, 21);
aButton.frame = buttonRect;
[aButton addTarget:self action:@selector开发者_如何学Go(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[aButton addTarget:self action:@selector(thisButton:) forControlEvents:UIControlEventTouchUpInside];
[aButton setTitle:@" " forState:UIControlStateNormal];
[gameScroll addSubview:aButton];
You're registering 2 different selectors for same events type. What will happen - the second one will override the first one. What is the point of this? May be you have a typo in your code sample, but anyway, you can register different selectors for different events. And if you're creating your buttons in the loop it's not a problem, since each time it will register a different object for this target. Your function will look like this probably:
- (void) buttonClicked:(id) sender
{
// your code
}
where the sender
is the object, which sends the selector to a target. In this case your button.
As for them running simultaneously... Do they run on different threads? Usually GUI runs only on main thread, so it will not happen simultaneously if this is a concern.
Hope it answers your question
It is meaningful to have multiple actions for different types of control events.
For same control event, those different actions would get invoked. Are you going to do same task in those different actions?
If you want to do different task in those different actions, cannot you do the same using some condition in the only one same action?
精彩评论