Reputation: 8473
I'm building calculator on the iphone for learning purposes.
I have a situation where I have multiple buttons that are Operations(+,-,/) and multiple buttons that are Operands e.g. 1,2,3 etc.
So all the the Operations connect to a operationPressed method in my viewController.
Is there a way in the UI builder to identify each UIButton other than using the Text for the button in the view?
What would be best practice?
Update
What about the Identity Label that I can set in the UI builder. can I reference that?
The reason I ask is I want to identify the button but say '/' but the text on the button would be '÷' so that is why i need some other string identifier which ultimately can be pass as an argument to my model. http://cl.ly/3H1j032f1M1d3A2Y3501
Upvotes: 0
Views: 2035
Reputation: 1107
You can define tags for your buttons, either in .xib or in code (button.tag = 123)
Define your IBAction with the sender, and check for which button was pressed.
- (void) operationPressed: (id) sender
{
UIButton *op = (UIButton *) sender;
switch(op.tag)
{
case 1: break; // op 1
case 2: break; // op 2
...
}
}
[Edit: Mar 2, 2012] using Storyboard
While in storyboard scene, select the UIButton, then in the right pane, go to button properties, scroll down to see button's view properties, you can set the tag value there.
Upvotes: 1
Reputation: 15597
The way this is typically handled is to set each button's tag
property to some unique integer value, and write action methods that take a sender
argument, for example:
- (void)operationPressed:(id)sender
{
// cast the argument to a more specific type
UIButton *button = (UIButton *) sender;
// get the view's tag
NSInteger tag = [button tag];
// Do whatever it was you were going to do...
}
EDIT
Here's the declaration of the tag
property from UIView.h
:
@property(nonatomic) NSInteger tag; // default is 0
Upvotes: 2
Reputation: 52227
Before you define tags for each button in Interface Builder, you could also create an outlet for each of them and connect it in Interface Builder
- (void)operationPressed:(id)sender
{
if(self.operationMultiplyButton == sender){
} else if(…) {
}
}
Personally I try to avoid solutions using tags, as in my opinion they head to redundant information: A pointer is a unique value already, instead it increases the need of documentation.
Upvotes: 0