NSMutableArray UIButtons Action? - iphone

I am Creating UIButtons programmatically and Then Store these UIButtons in NSMutableArray. All these UIButtons have Some Text as Titles. I have No Outlet for These UIButtons. Now I want to Assign the Title of UIButton to UIlabel when I touch or Click some UIButton. But the problem for me is this: how can I perform the function on these UIButtons. Because I created UIButtons programmatically and also these UIButtons have No Outlet. Here is my code to create Buttons:
saveBtn = [[NSMutableArray alloc] init];
for (int i=0; i<30; i++) {
if (btnn>8) {
UIButton *btn = [UIButton
buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(200.0 , spacey, 30.0, 30.0);
int idx;
idx = arc4random()%[arr count];
NSString* titre1 = [arr objectAtIndex:idx];
[btn setTitle:titre1 forState:UIControlStateNormal];
spacey=spacey+30;
spacex = 80;
btnn = 0;
}
else {
btnn++ ;
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(spacex, spacey, 30.0, 30.0);
int idx;
idx = arc4random()%[arr count];
NSString* titre1 = [arr objectAtIndex:idx];
[btn setTitle:titre1 forState:UIControlStateNormal];
spacex = spacex + 30;
[saveBtn addObject:btn];
[self.view addSubview:btn];
}
}
Please any one can guide me how can perfom action for these NSMutableArray UIButtons.

You can add actions to an UIButton programmatically using:
[button addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
- (void)buttonClicked:(UIButton *)btn
{
[btn setTitle:#"UnAutreTitre" forState:UIControlStateNormal];
}
Hope this helps.

Simply set tag and add target to the button. Later, you can get which button was tapped.

Create the action for the UIButton action, where you will be sending the (id)sender to the actionButtonFunction.
Assign sender to UIButton and then take the button title in NSString.
-(UIAction)buttonAction:(id)sender
{
UIButton *button = (UIButton *)sender;
NSString *buttonTitle = button.text;
// further code goes here
}

Related

How to have a method for each UIButton in an array

I have an array of UIButtons in the following code. Problem I'm having is that I need a unique method associated with each button. At the moment any button that's pressed all use the action:#selector(buttonPressed:)
I'm stuck on how to have a method hooked up to each button.
// Create buttons
NSMutableArray* buttonArray = [NSMutableArray array];
NSArray * myImages = [NSArray arrayWithObjects:#"category-cafe-unsel.png", #"category-food-unsel.png", #"category-clothing-unsel.png", #"category-health-unsel.png", #"category-tech-unsel_phone.png" , #"category-tech2-unsel.png", #"catefory-theatre-unsel.png", #"category-travel-unsel.png", nil];
// only create the amount of buttons based on the image array count
for(int i = 0;i < [myImages count]; i++)
{
// Custom UIButton
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(0.0f, 20.0f, 52.0f, 52.0f)];
[btn setTitle:[NSString stringWithFormat:#"Button %d", i] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:[myImages objectAtIndex:i]] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[buttonArray addObject:btn];
}
thanks for any help
:)
Best option is to use same method for all buttons.For that you should use tags. So each button has its own tag.
btn.tag = i;
Here tag number will be used for differentiating which button was called.
And then in the method you can get the tags, this can also be done with a switch-statement:
-(void)buttonPressed:(UIButton*)sender
{
if( sender.tag == 1 ){
} else {
}
}
Use following code:
-(void)buttonPressed:(UIButton*)sender
{
UIButton *btn = sender;
for(int i = 0;i < [myImages count]; i++)
{
if (i == [btn tag]) {
//Your code
break;
}
}
}
It's completly working fine. When you'll get Tag value, you can perform operations as per tag value.
Thanks,
Hemang.
[btn addTarget:self action:#selector(NSSelectorFromString([NSString stringWithFormat:#"button%d", i])) forControlEvents:UIControlEventTouchUpInside];
And the corresponding actions would be:
-(void)button1:(UIButton*)sender
-(void)button2:(UIButton*)sender
-(void)button3:(UIButton*)sender
-(void)button4:(UIButton*)sender
and so forth.
However, alternatively consider having one action method only and using tags to separate the buttons within the action method.

how to creating dynamic buttons iphone xcode?

I want to create uibuttons dynamically. so i for loop to create button with tag and added to view.
all buttons performs the same action with respect to its tag value... but i want to change the propery of the button. Therefore i need to get the uibutton using the tag value...
my code...
UIButton *button2;
//view did load
int width = 30;
for(int i = 1; i <= 5; i++)
{
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self action:#selector(ratingAction:) forControlEvents:UIControlEventTouchUpInside];
[button2 setBackgroundImage:[UIImage imageNamed:#"star1.png"] forState:UIControlStateNormal];
button2.tag = i;
button2.backgroundColor = [UIColor clearColor];
button2.frame = CGRectMake(width, 78, 15, 15);
[self.view addSubview:button2];
width = width +30;
}
-(void)ratingAction:(id*)sender
{
// here using the tag value i want to get the button and change the background image….
// for example i want to change the background for tag values 1,3,6,7 ,8…
}
Use viewWithTag function of UIView to access your UIButton using the tag value.
See in Documentation viewWithTag
Use it as below.
UIButton* myButton = (UIButton*)[mySuperView viewWithTag:1];
UIButton* myButton = (UIButton*)[mySuperView viewWithTag:3];
UIButton* myButton = (UIButton*)[mySuperView viewWithTag:6];
.........
-(void)ratingAction:(id*)sender
{
// here using the tag value i want to get the button and change the background image….
// for example i want to change the background for tag values 1,3,6,7 ,8…
if ([sender isKindOfClass:[UIButton class]])
{
UIButton *temp=(UIButton*)sender;
if ([temp tag]==1 || [temp tag]==3 || [temp tag]==6 || [temp tag]==7 )
{
[temp setBackgroundColor:[UIColor redColor]];
}
}
}
Check this code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
int y = 100;
for (int i=0; i<=5; i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80, y, 160, 40);
[button setTitle:[NSString stringWithFormat:#"Button-%i", i] forState:UIControlStateNormal];
// [button set
[self.view addSubview:button];
y=y+60;
}
}
-(void)aMethod:(id)sender{
UIButton *button = sender;
int y = 100;
int i = 5;
for (int x=0; x<=i; x++) {
NSString *frameString = [NSString stringWithFormat:#"{{80, %i}, {160, 40}}", y];
if ([NSStringFromCGRect(button.frame) isEqualToString:frameString]) {
NSLog(#"button %i clicked..", x);
}
y= y+60;
}
}

How to set the background image for the particular index of the button in iPhone?

I have created buttons dynamically and now I want to set the background for a particular index of the buttons.
Here is my sample snippet:
In the interface file:
UIButton *answerBtn;
#property (nonatomic, retain) UIButton *answerBtn;
for(int i = 0; i < [myArray count]; i++) {
answerBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[answerBtn setFrame:CGRectMake(30, x, 260, 40)];
answerBtn.tag = i;
[answerBtn setTitle:[answerList objectAtIndex:i] forState:UIControlStateNormal];
[self.view addSubview: answerBtn];
}
In my case, I want to set the button background in different methods.
-(void) custom Method
{
if(indexValue == correctIndex) // Values are 2
{
// so I want to set the background image for the second button
[answerBtn setBackgroundImage:[UIImage imageNamed:#"selected_correct_answer.png"] forState:UIControlStateNormal];
}
}
But it doesn't set the corresponding index, so how can I do that?
Try this
for(int i = 0 ; i < [myArray count] ; i++ )
{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setTag:i];
[btn setFrame:CGRectMake(30, x, 260, 40)];
[btn addTarget:self action:#selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
- (IBAction) btnClicked::(id)sender
{
UIButton *btnTapped=(UIButton *)sender;
for(UIView *btn in self.view.subviews)
{
if([btn isKindOfClass:[UIButton class]])
{
UIButton *btnComp = (UIButton*)btn;
if(btnComp.tag == btnTapped.tag)
[btnComp setBackgroundImage:[UIImage imageNamed:#"selected_correct_answer.png" forState:UIControlStateNormal];
else
[btnComp setBackgroundImage:[UIImage imageNamed:#"default_image.png" forState:UIControlStateNormal];
}
}
}
Use -(void)custom:(id)sender instead of -(void)custom.
In the sender you can have the index of the button.
UIButton *answerBtn = (UIButton *)[self objectWihTag:1]

Can I add OBject of button to NSMutableArray?

I am trying to create number of buttons on view programatically and for that I need array, so can I add button object in NSMutableArray?
Yes you can do that see the following code
// Create buttons for the sliding menu. For simplicity I create 5 standard buttons.
NSMutableArray *buttonArray = [[NSMutableArray alloc] init];
for(NSInteger i = 0; i < [self.slideMenuArray count]; i++)
{
// Rounded rect is nice
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
NSString *title=[slideMenuArray objectAtIndex:i];
[btn setFrame:CGRectMake(0.0f, 4.0f, 90.0f, 20.0f)];
[btn setTitle:[NSString stringWithString:title] forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColor clearColor]];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[[btn titleLabel] setFont:[UIFont systemFontOfSize:12]];
[btn addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
UIImage *backgroundView;
if(i==0)
backgroundView= [UIImage imageNamed:#"btnclk.png"];
else
backgroundView= [UIImage imageNamed:#"btn.png"];
[btn setBackgroundImage:backgroundView forState:UIControlStateNormal];
[buttonArray addObject:btn];
}
You can retrieve the added button objects like this-
for(int i = 0; i < [buttonArray count]; i++)
{
UIButton *btn = [buttonArray objectAtIndex:i];
// Move the buttons position in the x-demension (horizontal).
CGRect btnRect = btn.frame;
btnRect.origin.x = totalButtonWidth;
[btn setFrame:btnRect];
}
sure you can, and remember that when you do, every button or other object will be retained bu the array and released when you remove it from the array...
Yes, NSMutableArray can hold any objects

how to lisent to each button for iphone

i have created 4 dynamic buttons but how to write method on each of them
for (i = 1; i <= [a1 count]-1; i++)
{
NSString *urlE=[a1 objectAtIndex:1];
NSLog(#"url is %#",urlE);
#pragma mark buttons
CGRect frame = CGRectMake(curXLoc, 10, 60, 30);
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = frame;
[button setImage:[UIImage imageNamed:#"tab2.png"] forState:UIControlStateNormal];
[button setTitle:(NSString *)#"new button" forState:(UIControlState)UIControlStateNormal];
[button addTarget:self action:#selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
curXLoc += (kScrollObjWidth1);
[self.view addSubview:button];
}
-(void)buttonEvent:(id)sender {
NSLog(#"new button clicked!!!");
if (sender == ??) how to tell button 1 ,2,3,4
{
}
}
You should give a .tag to each button on creation
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.tag = i; // <-- here
...
With this, you could identify the button by .tag.
-(void)buttonEvent:(UIButton*)sender {
NSLog(#"new button clicked!!!");
if (sender.tag == 2) {
NSLog(#"2nd button clicked.");
...
You can specify a separate selector for each button using NSSelectorFromString to dynamically generate selector names.
For example
NSString *selectorName = [NSString stringWithFormat:#"button%dEvent:", i];
[button addTarget:self action:NSSelectorFromString(selectorName) forControlEvents:UIControlEventTouchUpInside];
-(void)button1Event:(UIButton*)sender {}
-(void)button2Event:(UIButton*)sender {}
-(void)button3Event:(UIButton*)sender {}
-(void)button4Event:(UIButton*)sender {}