TEMPESTINI.NET

Observations in Software Development

Archive for the ‘iPhone Development’ Category

Passing Values on the Tag Attribute

Posted by Rick Tempestini on May 31, 2009

I’m learning to develop in XCode for the iPhone.  Being a long time Microsoft developer I admittedly struggle with some of the most simple things in this new XCode/Objective-C world.  One of my recent struggles was when I  attempted to assign several controls in Interface Builder (or, IB for short) unique Tag attributes and then read them in the IBAction method.  I searched far and wide and finally found the answer.

In my scenario, I had several buttons in my View that I wanted to handle with a single method.  I needed to find a way to differentiate between them to find out which one the user clicked.

Solution:

In IB I created three buttons as shown below.  I then selected each one separately and assigned it a unique ‘Tag’ attribute.  The ‘Tag’ attribute is located on the ‘Button Attributes’ tab of the Inspector.

TagExample

That part wasn’t much of a challenge.  What, unfortunately, was a challenge was getting this value from within the IBAction method.  First, the action method is declared in my ViewController.h file like any other IBAction method:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController {
}

- (IBAction)push:(id)sender;

@end

Next, the important part.  I had to find a way to get the actual value in my push method.  After several unsuccessful variations of trying to call [sender tag] directly, I found the answer (shown in bold below):

@implementation ViewController

- (IBAction)push:(id)sender
{
 UIButton *btn = (UIButton *)sender;
 NSInteger tag = [btn tag];
 NSLog(@"Tag: %d", tag);

The answer is actually very simple.  Since sender is a generic object type I had to cast it to a UIButton before I could get to the tag property.

Stay tuned.  At this rate there are many more of these quick samples on the way…

Posted in iPhone Development | 1 Comment »

 
Follow

Get every new post delivered to your Inbox.