how to creating dynamic buttons iphone xcode? - iphone

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;
}
}

Related

Add buttons to UIScrollview

I want them to be shown on the screen 4 at a time so I'm thinking about creating a UIScrollview for that and adding a subview with the buttons on it. How can I add let's say about 20 buttons since I can't have them all on the screen?
How about adding it your button in array.
Something like this: (just a snippet)
int row = 0;
int column = 0;
for(int i = 0; i < _thumbs.count; ++i) {
UIImage *thumb = [_thumbs objectAtIndex:i];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*60+10, row*60+10, 60, 75);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[scrollView addSubview:button];
// If you want to show only 4 buttons, just tweak it here. You can do this method in anyway you like
if (column == 4) {
column = 0;
row++;
} else {
column++;
}
}
[scrollView setContentSize:CGSizeMake(300, (row+1) * 60 + 10)];
Hope this helps.

NSMutableArray UIButtons Action?

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
}

How to get the information about the sender in the case here

I am creating UIButtons inside a loop as shown below.
for(int i = 1; i <= count; i++){
if(i ==1){
UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 10, 40, 40)];
[btn1 setImage:image2 forState:UIControlStateNormal];
[self addSubview:btn1];
continue;
}
x = x + 40;
y = y + 50;
UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(x , y, 40, 40)];
[btn2 setImage:image1 forState:UIControlStateNormal];
[btn2 addTarget:self action:#selector(buttonPressed)
forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btn2];
}
And I handle the UIButton clicked events as
-(void) buttonPressed{
}
I need the information about which button I have clicked in the event handling method. I need to ge the frame of the clicked button. How can I alter this code to get the information about the sender.
Add a tag to your button while it is created like btn.tag=i; and re define your method like this
-(void) buttonPressed:(id)sender{
// compare sender.tag to find the sender here
}
What you should do is add these lines in your code:
for(int i = 1; i <= count; i++)
{
if(i ==1){
UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 10, 40, 40)];
[btn1 setImage:image2 forState:UIControlStateNormal];
[btn1 setTag:i]; // This will set tag as the value of your integer i;
[self addSubview:btn1];
continue;
}
x = x + 40;
y = y + 50;
UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(x , y, 40, 40)];
[btn2 setImage:image1 forState:UIControlStateNormal];
[btn2 setTag:i]; // also set tag here.
[btn2 addTarget:self action:#selector(buttonPressed)
forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btn2];
}
And now change your IBAction like this:
-(void) buttonPressed: (id)sender
{
if(sender.tag==1) // determine which button was tapped using this tag property.
{
// Do your action..
}
}
Or you can do it this way..This way you copy the object thats in sender to this UIBtton object.
-(void) buttonPressed: (id)sender
{
UIButton *tempBtn=(UIButton *) sender;
if(tempBtn.tag==1) // determine which button was tapped using this tag property.
{
// Do your action like..
tempBtn.backgroundColor=[UIColor blueColor];
tempBtn.alpha=0.5;
}
}
So in this parameter sender its going to hold your UIButton on which you interact and you can access its properties like tag, text etc. Hope it helps..

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]

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 {}