on one viewController of my app there is a long list of 20 or so buttons added programmatically, all which i want to call the same method, but to identify themselves through their button tag, but i ran into a problem that has set me back a few hours of research and attempts.The basic problem is i dont quite know how to access a programmatically created button in any other method than the method that they were initialized in.
My questions summerized:
1) if i were to create the button in the viewDidLoad method, how can I access it in a void method that i create?
2) How can i access those button tags in the created void method?
Here is the code that i have so far, but it is producing errors that ill explain below.
-(void)viewDidLoad{
float itemScrollerXdirection =0;
float itemScrollerYdirection =0;
float ySize =70.0;
float xSize = 70.0;
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(itemScrollerXdirection,itemScrollerYdirection,xSize,ySize);
[button addTarget:self action:@selector(itemSelected) forControlEvents:UIControlEventTouchUpInside];
button.tag =1;
[button setTitle:@"button1" forState:UIControlStateNormal];
[itemScroller addSubview:button];
}
//no errors in the above code
-(void)itemSelected{
if ([sender tag] == 1) { //Gets error "Use of undeclaired identifier 'sender'"
button.hidden = YES; //Gets error "Use of undeclaired identifier 'button1'"
}
}
We aren't working in the mystical relm of ruby, things need to be initialized and stored somewhere inorder for you to call them, try this:
#.h
@interface MyController : UIViewController{
NSMutableArray *buttons;
}
#.m
-(void)init // Or whatever you use for init
{
buttons = [[NSMutableArray alloc] init];
}
-(void)viewDidLoad{
//blah blah (what you already have)
[button addTarget:self action:@selector(itemSelected:) //Add ":"
forControlEvents:UIControlEventTouchUpInside];
button.tag =0;
[buttons addObject:button] //Add button to array of buttons
//blah blah (what you already have)
}
-(IBAction)itemSelected:(id)sender{
UIButton* button = [buttons objectAtIndex:sender.tag]
button.hidden = YES;
}
Note: I'm doing this from memory on, so it might not work perfectly.
#.h
@interface MyController : UIViewController{
UIButton *buttons;
}
#.m
-(void)viewDidLoad{
float itemScrollerXdirection =0;
float itemScrollerYdirection =0;
float ySize =70.0;
float xSize = 70.0;
self.button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.button.frame = CGRectMake(itemScrollerXdirection,itemScrollerYdirection,xSize,ySize);
[self.button addTarget:self action:@selector(itemSelected) forControlEvents:UIControlEventTouchUpInside];
self.button.tag =1;
[self.button setTitle:@"button1" forState:UIControlStateNormal];
[itemScroller addSubview:button];
}
//no errors in the above code
-(void)itemSelected
{
if ([sender tag] == 1)
{
self.button.hidden = YES;
}
}