Reputation: 19303
I've declared an enum like so:
typedef enum
{
firstView = 1,
secondView,
thirdView,
fourthView
}myViews
My goal is that a UIButton
will trigger another function with the uiButton
sender.tag
and that function will know to convert the integer to the correct view. I'm aware that I can just create an array with the names of the views but I am looking for something smarter than that using the declared enum.
Example:
-(void)function:(UIButton *)sender
{
...
...
NSLog(@"current View: %@",**converted view name from sender.tag);
}
Thanks
Upvotes: 0
Views: 1730
Reputation: 130072
Well, the best solution is to actually store the views. You can also use a IBOutletCollection
to create the array. Declaring an enum
is just another way to store names.
self.views = @[firstView, secondView, thirdView, forthView];
...
button.tag = [self.views indexOfObject:firstView];
...
- (void)buttonTappedEvent:(UIButton*)sender {
UIView* view = [self.views objectAtIndex:sender.tag];
}
PS: converting tag
into enum
is trivial, it's just
myViews viewName = sender.tag
, possibly with a cast myViews viewName = (myViews) sender.tag
Upvotes: 3
Reputation: 1706
What I normally do is declare it to dictionary for once using dispatch once
static NSDictionary* viewList = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
viewList = [NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInt:1], @"firstView",[NSNumber numberWithInt:2], @"secondView",[NSNumber numberWithInt:2], @"thirdView",@"secondView",[NSNumber numberWithInt:3], @"fourthView",
nil];
});
and find with tag like this:
-(void)function:(UIButton *)sender
{
NSLog(@"current View: %@",[viewList objectForKey:[NSNumber numberWithInt:sender.tag]);
}
Upvotes: 0
Reputation: 11607
How about storing it inside a NSMutableDictionary ?
NSMutableDictionary *viewList = [[NSMutableDictionary alloc] init];
for(int i = 1; i <= 4; i++)
{
[viewList setObject:@"firstView" forKey:[NSString stringWithFormat:@"%d", i]];
}
...
-(void)buttonTappedEvent:(id)sender
{
UIButton *tappedButton = (UIButton *)sender;
NSLog(@"current view: %@", [viewList objectForKey:[NSString stringWithFormat:"%d", tappedButton.tag]]);
}
Upvotes: 0