Reputation: 1121
Here is my task.. How it is working now ? If i click over the button, I am getting 5 text field one by one. But i want to create a text field on every click of a button.
Eg: First click should create 1st text field
Second Click should create 2nd text field
Third Click should create 3rd text field
Fourth Click should create 4th text field
Fifth Click should create 5th text field
Here is my code :
- (IBAction)button_click:(id)sender
{
float xaxis = 60;
float yaxis = 130;
for(int i=0;i<5;i++)
{
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(xaxis,yaxis,200,30)];
textField.tag = i;
textField.backgroundColor = [UIColor purpleColor];
[self.view addSubview:textField];
yaxis = yaxis+50;
}}
Upvotes: 0
Views: 112
Reputation: 308
You are using for loop on button_click method, which executes five times. So it is adding five text fields.
Remove for loop and this will app one text field on each button click. Also you need to define variables xaxis,yaxis in viewDidLoad method.
Updated code
@interface myController : UIViewController {
float xaxis;
float yaxis;
int i;
}
@end
- (void)viewDidLoad
{
xaxis = 60;
yaxis = 130;
i = 1;
}
- (IBAction)button_click:(id)sender
{
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(xaxis,yaxis,200,30)];
textField.tag = i;
textField.backgroundColor = [UIColor purpleColor];
[self.view addSubview:textField];
yaxis = yaxis+50;
i++;
}
Upvotes: 1
Reputation: 516
First you need to remove the for loop.there is no need of for loop.Instead of that create a variable for count.and initialise it with 0 and create another one variable for Y axis.
For Ex:
var count = 0
var yAxis = 60
Then in the outlet action of button you need to create button programically
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(20,yAxis,200,30)];
Then you need to add this on to your view.
[self.view addSubview:textField];
Then you need to increase the height of yAxis.
yAxis = yAxis+60
count = count+1
Remeber to add the if condition for check the count
Upvotes: 0