Search code examples
iphoneiosobjective-cuitextfielddynamic-typing

Adding more UITextField on View when Typing On A UITextField


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 ...


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