user3540000 user3540000 - 10 months ago 57
iOS Question

Adding uitextfields dynamically

I have a

and 4 buttons on that. I already have one text field. If I press the 2 button on action sheet I have to add 1 more textfield and 3rd button I have to add 2
s and so on upto 5 buttons. and the scenario is if I press the 5th button 5 textfields should be added and again if I press 1st button remaining 4 textfields should go basing on that I have to set contentSize of the scrollview too. I have written this:

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex

float yAxis = _adult1TF.frame.origin.y+_adult1TF.frame.size.height+10;
float xAxis1 = _adult1TF.frame.origin.x;
float xAxis2 = _child1TF.frame.origin.x;
float width = _child1TF.frame.size.width;
for(int i=1;i<(buttonIndex+1);i++)
UILabel * roomLabel2 = [[UILabel alloc]initWithFrame:CGRectMake(xAxis1, yAxis, width, 20)];
roomLabel2.text = [NSString stringWithFormat:@"Room%d:",i+1];
[_scroll addSubview:roomLabel2];
UILabel * adultLabel = [[UILabel alloc]initWithFrame:CGRectMake(xAxis1, roomLabel2.frame.size.height+roomLabel2.frame.origin.y+10, width, 20)];
adultLabel.text = @"Adults";
[_scroll addSubview:adultLabel];
UILabel * childLabel = [[UILabel alloc]initWithFrame:CGRectMake(xAxis2, adultLabel.frame.origin.y, width, 20)];
childLabel.text = @"Children";
[_scroll addSubview:childLabel];

UITextField * adultTF = [[UITextField alloc]initWithFrame:CGRectMake(xAxis1, adultLabel.frame.size.height+adultLabel.frame.origin.y+10, width, 30)];
adultTF.text = @"1";
[_scroll addSubview:adultTF];

UITextField * childTF = [[UITextField alloc]initWithFrame:CGRectMake(xAxis2, adultTF.frame.origin.y, width, 30)];
childTF.text = @"0";
[_scroll addSubview:childTF];
adultTF.borderStyle = childTF.borderStyle = UITextBorderStyleRoundedRect;
yAxis = adultTF.frame.size.height+adultTF.frame.origin.y+10;
_searchButton.frame = CGRectMake(_searchButton.frame.origin.x, yAxis+10, _searchButton.frame.size.width, _searchButton.frame.size.height);
_scroll.contentSize = CGSizeMake(_scroll.frame.size.width, _searchButton.frame.size.height+_searchButton.frame.origin.y+15);

The problem with this is that I am able to add the textfields but again if I press the 1st button the remaining textfields are not going.

Please tell me how to achieve this issue.

Answer Source

You have mentioned that action sheet has liminted number of buttons. So you create all the textfields intially and hide those text fields. When ever user clicks on the action sheet button, you just hide/unhide the textfields based on the button index.

If you have more number of buttons(want to create more text fields) you can use UITableView class to create the multiple objects with resuse funcatinality.