how to make the UITextField on different frame?

2019-06-11 04:39发布

问题:

i have an array for my UITextField to be created. but the UITextField remain on the same Frame?Here is my code. It create a new UITextField when you press the button.

-(IBAction)textFieldcreating{


    textfieldform = [[NSMutableArray alloc] init];
    textField1 = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 100, 40)];
    textField1.borderStyle = UITextBorderStyleRoundedRect;
    textField1.font = [UIFont systemFontOfSize:15];
    textField1.placeholder = @"enter text";
    textField1.autocorrectionType = UITextAutocorrectionTypeNo;
    textField1.keyboardType = UIKeyboardTypeDefault;
    textField1.returnKeyType = UIReturnKeyDone;
    textField1.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField1.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;    
    textField1.delegate = self;

    [textfieldform addObject:textField1];

    int counter;
    counter = 0;
    if(counter < [textfieldform count])
    {


            textField1.frame = CGRectMake(textField1.frame.origin.x+30, textField1.frame.origin.x+40, textField1.frame.size.width+40, textField1.frame.size.height+50);
            [self.view addSubview:textField1];

        counter++;
    }

}

回答1:

What you are doing is creating a new Array and keeping the xOrigin and yOrigin same for all the UITextViews!

Do something like this.

In .h file, declare

@property (nonatomic, retain) NSMutableArray *textfieldform;
@property (nonatomic, readwrite) int yOrigin;

in .m file, in viewDidLoad function,

self.textfieldform = [NSMutableArray arrayWithCapacity:0];
yOrigin = 0;

now, your function looks like this.

-(IBAction)textFieldcreating{


    //textfieldform = [[NSMutableArray alloc] init]; NO NEED OF THIS LINE NOW
    textField1 = [[UITextField alloc] initWithFrame:CGRectMake(10, yOrigin, 100, 40)];
    textField1.borderStyle = UITextBorderStyleRoundedRect;
    textField1.font = [UIFont systemFontOfSize:15];
    textField1.placeholder = @"enter text";
    textField1.autocorrectionType = UITextAutocorrectionTypeNo;
    textField1.keyboardType = UIKeyboardTypeDefault;
    textField1.returnKeyType = UIReturnKeyDone;
    textField1.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField1.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;    
    textField1.delegate = self;

    [textfieldform addObject:textField1];

    yOrigin = yOrigin + 40 + 10; //old yorigin + btn height + y offset
}

If you want changes in xOrigin too, then take another variable with xOrigin