Adding multiple uicontrollers on view

A

If we create multiple controllers programmatically, we generally use for loop but we can add the same controllers by using the methods,

example:

1. By using for loop

 

for (int i = 0; i < 3; i++)

{

UITextField *textField= [[UITextField alloc] initWithFrame:CGRectMake(50, 20+40*i, 117, 30)];

textField.borderStyle = UITextBorderStyleRoundedRect;

textField.font = [UIFont systemFontOfSize:15];

textField.placeholder = @”enter text”;

textField.autocorrectionType = UITextAutocorrectionTypeNo;

textField.keyboardType = UIKeyboardTypeDefault;

textField.returnKeyType = UIReturnKeyDone;

textField.clearButtonMode = UITextFieldViewModeWhileEditing;

textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

textField.delegate = self;

textField.tag = i;

[self.view addSubview:textField];

}

here, we have to get controllers by tags or by array outside the loop and bit difficult to set position, if controllers are not be aligned

 

2. By using methods

 

We can create the method like this

-(UITextField *)getTextField:(CGRect)frame

{

UITextField *textField= [[UITextField alloc] initWithFrame:frame];

textField.borderStyle = UITextBorderStyleRoundedRect;

textField.font = [UIFont systemFontOfSize:15];

textField.placeholder = @”enter text”;

textField.autocorrectionType = UITextAutocorrectionTypeNo;

textField.keyboardType = UIKeyboardTypeDefault;

textField.returnKeyType = UIReturnKeyDone;

textField.clearButtonMode = UITextFieldViewModeWhileEditing;

textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

textField.delegate = self;

return textField;

}

and just call the above method as

UITextField *firstName = [self getTextField:CGRectMake(167, 20, 117, 30)];

[self.view addSubview:firstName];

UITextField *lastName = [self getTextField:CGRectMake(167, 60, 117, 30)];

[self.view addSubview:lastName];

UITextField *phoneNo = [self getTextField:CGRectMake(167, 100, 117, 30)];

[phoneNo setKeyboardType:UIKeyboardTypePhonePad];

[self.view addSubview:phoneNo];

 

Second method is also helpful when we add more controllers later..

 

 

 

 

 

About the author

dattatraya.surwase
By dattatraya.surwase

Category