Tuesday, December 15, 2009

Retrieve properties of the sender

In last article, Hello iPhone, using View-Based Application, the triggered Action Method modify the text of the Label, without any knowledge of event source.

In this article, the title of the source button will be displayed on the screen, to show how to retrieve the properties of the Sender.

Modify helloiphoneViewController.xib to add one more button, rename the two buttons with the name Button 1 and Button 2. Repeat the step in the last article to Connect the Action from Botton 2 to buttonPressed.

Interface Builder

Modify the method buttonPressed inside the file helloiphoneViewController.m

-(IBAction)buttonPressed:(id)sender{
NSString *title = [sender titleForState:UIControlStateNormal];
NSString *newText = [[NSString alloc] initWithFormat:@"Hello! %@ Pressed", title];


labelText.text = newText;
[newText release];
}

[sender titleForState:UIControlStateNormal] return the title of the sender, such that we can identify which button pressed to trigger the event buttonPressed.

Back to Xcode, Build and Run the application again.
Screenshot