Question

I am new to iOS development. I want to create UITextFields dynamically on depending the condition. Condition is that if I start typing on first UITextField it will create one more UITextField in the bottom and will create the third UITextField when i start typing on second one. Similarly i want to delete the bottom text if there is no text in the upper UITextField. Any help will be appreciated ...

Was it helpful?

Solution

Try this

Step:1 decleare this tagCounter variable in global

 int tagCounter=1;

Step:2 set your First UITextField tag and Delegate

 [MyFirstTextField setTag:tagCounter];
 [MyFirstTextField setDelegate:self];
 tagCounter+=1;

Step:3 write below two method to create new textfield and remove textfield

-(void)CreateNewTextField:(float)FromTop withTag:(int)Tag
{
     UITextField *NewTextField=[[UITextField alloc] initWithFrame:CGRectMake(0.0f, FromTop, 100.0f, 40.0f)];
     [NewTextField setDelegate:self];
     [NewTextField setTag:Tag];
     [[self view] addSubview:NewTextField];
}

-(void)RemoveTextField:(int)Tag
{
    for(UIView *sub in [[self view] subviews])
    {
        if([sub isKindOfClass:[UITextField class]])
        {
            if([sub tag]>=Tag)
            {
                [sub removeFromSuperview];
            }
        }
    }
}

Step:4 use the textField delegate method textFieldDidEndEditing to create new textField and remove textfield

   -(void)textFieldDidEndEditing:(UITextField *)textField
 {
    if([[textField text] isEqualToString:@""])
    {
        int CurrentTag=[textField tag];
        [self RemoveTextField:CurrentTag+1];
    }
    else
    {
        CGRect CurrentTextFieldFrame=[textField frame];
        [self CreateNewTextField:CurrentTextFieldFrame.origin.y+CurrentTextFieldFrame.size.height+20.0f withTag:tagCounter];
        tagCounter+=1;
    }
}

OTHER TIPS

Here's a tutorial on how to create UITextField from code.

The way you should implement it is, add the first text field, set it's delegate to self, and in the textFieldDidBeginEditing: method, you create another text field, sets it's delegate and create a button next to it. If you want to delete it, I would suggest adding the same tag for both UITextField and it's respective delete UIButton, then when a button is tapped, remove all views with that tag from the superview.

I would suggest trying everything step by step:

  • Creating a UITextField from code
  • Creating UIButton from code
  • Setting a tag to UIView (superclass of both UIButton and UITextField).
  • Implementing UITextField delegate method.
  • Adding a custom method to a UIButton (delete method).
  • Remove UIView from view based on tag.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top