How to create dynamic UITextField with different object name? - ios

I want to create dynamic UITextField with different object name.I have shown the code below for creating textfield dynamically. How can i create each textfield with different object name ?
for (int x=0; x < 4 ; x++)
{
CGRect txtFldFrame;
if (x==0)
txtFldFrame=CGRectMake(385, 620, 278, 45);
else
txtFldFrame=CGRectMake(385, txtFldFrame.origin.y+60, 278, 45);
[self createTxtImg:txtImgFrame createTextfield:txtFldFrame];
}
In the
createTextfield:(CGRect )txtfldframe
{
UITextField *txtFld1=[[UITextField alloc]init];
txtFld1.frame=txtfldframe;
[txtFld1 setTag:textChk];
txtFld1.borderStyle = UITextBorderStyleNone;
txtFld1.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
txtFld1.textAlignment=UITextAlignmentLeft;
txtFld1.textColor=[UIColor colorWithRed:17/255.0 green:61/255.0 blue:83/255.0 alpha:1];
txtFld1.font = [UIFont systemFontOfSize:22];
txtFld1.backgroundColor = [UIColor clearColor];
txtFld1.autocorrectionType = UITextAutocorrectionTypeNo;
txtFld1.returnKeyType = UIReturnKeyDone;
txtFld1.clearButtonMode = UITextFieldViewModeWhileEditing;
txtFld1.autocapitalizationType=UITextAutocapitalizationTypeNone;
txtFld1.delegate = self;
[subScrollView addSubview:txtFld1];
}

There is absolutely not a reason to create text fields with a different (unique name).
I'm pretty sure the reason you want the unique name, is so you can access them later in your code and edit their values, but here comes the trick: Use unique tag numbers.
Here is an example:
for (int i=0; i<4; i++) {
UITextField *myTextfield = [[UITextField alloc] initWithFrame:CGRectZero];
myTextField.tag = 200+i;
[self.view addSubview:myTextField];
}
Now we have created 4 text fields, which have tags 200, 201, 202 and 203
Later in code when we want to reference the second text field for example, all we have to do is this:
UITextField *myTextField = (UITextField *)[self.view viewWithTag:201];
now we have the control and we can get or set anything...
As a precaution I would suggest you check you actually got the UI element, by using:
if (!myTextField)
return;

Use following code to create textbox:
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(150, 12, 120, 25)];
[self.view addSubview:textField];
For another textbox just change the object name (textField)

I don't understand everything, because you gave not much information.
If you want to initialize multiple UITextFields:
UITextField *myTextField1 = [[UITextField alloc] init];
UITextField *myTextField2 = [[UITextField alloc] init];
UITextField *myTextField2 = [[UITextField alloc] init];
and so on...
If you want to do this on a random basis or a loop basis, i recommend to loop and put the objects into a dictionary with random keys like so:
NSMutableDictionary *myDict = [NSMutableDictionary dictionary];
for (int i=0; i<20; i++) {
UITextField *myTextfield = [[UITextField alloc] initWithFrame:CGRectZero];
[myDict setObject:myTextfield forKey:[NSString stringWithFormat:#"myTextfield%d", i]];
[myTextfield release];
}
NSLog(#"Dict: %#",myDict);

Related

How to delete UITextfield and entered data from it in iOS

I have develop one application and in that I have two UIButton named [+] and [-] and one UITextField default.
Now what I want is when I click on plus [+] button it should add one UITextField in UIView that is work perfectly to me but when I click on minus [-] button it should delete last created UITextField that is not working now for me.
How to manage that?
here is my code to plus[+] button.
- (IBAction)btnPlusClicked:(id)sender
{
scrollViewSpecialitiesTxtFields.hidden = FALSE;
float y;
y = (35 * txtSpecialityFieldCounter);
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, y, 120, 30)];
textField.delegate = self;
textField.borderStyle = UITextBorderStyleRoundedRect;
[arraySpecialitiesTxtFields insertObject:textField atIndex:arraySpecialitiesTxtFields.count];
scrollViewSpecialitiesTxtFields.contentSize = CGSizeMake(125, y+30);
[scrollViewSpecialitiesTxtFields addSubview:textField];
txtSpecialityFieldCounter++;
NSLog(#"txtSpecialityFieldCounter : %d",txtSpecialityFieldCounter);
}
here is my minus [-] button code
-(IBAction)btnMinusClicked:(id)sender
{
[scrollViewSpecialitiesTxtFields.subviews makeObjectsPerformSelector:#selector(removeFromSuperview)];
txtSpecialityFieldCounter--;
NSLog(#"txtSpecialityFieldCounter : %d",txtSpecialityFieldCounter);
float y;
y = (35 * txtSpecialityFieldCounter);
for(int i = 0 ; i < txtSpecialityFieldCounter; i++)
{
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, y, 120, 30)];
textField.delegate = self;
textField.borderStyle = UITextBorderStyleRoundedRect;
[arraySpecialitiesTxtFields insertObject:textField atIndex:arraySpecialitiesTxtFields.count];
scrollViewSpecialitiesTxtFields.contentSize = CGSizeMake(125, y-30);
[scrollViewSpecialitiesTxtFields addSubview:textField];
}
}
I know minus[-] button code is wrong but let me know changes
Create a global variable as NSMutableArray *myAddedTextfields and in viewDidLoad-> myAddedTextFields = [NSMutableArray array];
- (IBAction)plusAction:(id)sender
{
UITextField *textField1 = [[UITextField alloc]initWithFrame:CGRectMake(50, 50, 100, 20)];
textField1.text = #"hey how r u";
textField1.backgroundColor = [UIColor grayColor];
textField1.tag = 1;
[self.view addSubview:textField1];
[myAddedTextFields addObject:textField1];
}
- (IBAction)minusAction:(id)sender
{
UITextField *txtField = [myAddedTextFields objectAtIndex:myAddedTextFields.count -1]; //for deleting from the last textfield onwards.
[txtField removeFromSuperView];
[myAddedTextFields removeObjectIdenticalTo:txtField];
}
I have edited your method.. hope this helps.
Whenever you want to add an UITextField on a superview, set the tag of that component (UITextField).
And when you want to remove it from superview then get the reference of that component (UITextField) using the tag and remove it from the superview.
Here is an example that may be helpful to you:
-(IBAction)plusAction:(id)sender
{
UITextField *textField1 = [[UITextField alloc]initWithFrame:CGRectMake(50, 50, 100, 20)];
textField1.text = #"hey how r u";
textField1.backgroundColor = [UIColor grayColor];
textField1.tag = 1;
[self.view addSubview:textField1];
}
-(IBAction)minusAction:(id)sender
{
UITextField * textfield = (UITextField *)[self.view viewWithTag:1];
[textfield removeFromSuperview];
}
Yes, you could use the tag option. Or you could use an NSArray holding your UITextFields.
#interface MyTextFieldViewClass ()
#property (nonatomic, retain) NSMutableArray *textFields;
#end
#implementation MyTextFieldViewClass
- (void)viewDidLoad {
[super viewDidLoad];
self.textFields = [NSMutableArray array];
}
- (IBAction)addTextField:(id)sender {
UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(50, 50, 100, 20)];
[self.textFields addObject:tf];
[self.view addSubview:tf];
}
- (IBAction)removeTextField:(id)sender {
UITextField *tf = [self.textFields lastObject];
[tf removeFromSuperview];
[self.textFields removeLastObject];
}
#end
This would be a little better since you do not have to iterate over all the views/ids that exist in self.view.subviews. Also, using the tag might not be reliable since you always want to remove the last item, so you would either need to keep the last item number in memory or you need to iterate over all the subviews in order to find the UITextField with the highest tag and in order to remove it.

Create controls in UIView at runtime?

I have one UITextField and a button in a view.
Once a button is pressed, value in text field need to be searched fieldID column in core data table and get value[comma separated].
Separate the string by comma and assign values to array.
A new UIView needs to be inserted in the main screen and place N number[count of array] of labels and textfields and align.
I am able to do 1, 2 and UIView creation.
Can anybody help me to create N number of controls in sub UIView at runtime?
for(int i=0;i<self.yourArray.count; i++)
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10,80*i+60,self.view.frame.size.width-20,60)];
label.text = [yourArray objectAtIndex:i];
[self.view addSubview:label];
}
Please Explain your problem more clearly !
May be your array count is very large so take a scroll view also in your view
UIScrollView* yourScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(yourView.frame.origin.x, yourView.frame.origin.y,yourView.frame.size.width,yourView.frame.size.height)];
for(int i= 0; i< 10;i++)
{
UILabel* lbl = [[UILabel alloc]initWithFrame:CGRectMake(10, y, 50, 21)];
lbl.text = #"";
UITextField* txtField = [[UITextField alloc]initWithFrame:CGRectMake(lbl.frame.origin.x+10 , y, 200, 21)];
txtField.text = #"";
[yourScrollView addSubview:lbl];
[yourScrollView addSubview:txtField];
y = y+30;
}
[yourView addSubview:yourScrollView];

How to create dynamic uitextfiled inside a loop and make all them editable mode?

I am continuously facing problem to create uitextfield programmatically inside a loop and make all them in editable mode?
I have created successfully text fields inside the loop but problem is that. the last one i.e. the last text field is in editable mode.
EX:
suppose an array (myarray) has 5 values.
-(void)createDynamic_textfld{
UITextField *roomratetxt;
UIScrollView *scrlsummery;
NSMutableArray *myarray = [NSMutableArray arrayWithObjects:#[#"one",#"two",#"three",#"four",#"five"], nil];
for (int i = 0; [myarray count]; i ++){
roomratetxt = [[UITextField alloc]init];
roomratetxt.frame = CGRectMake(200, 0, 90, 20);
roomratetxt.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"lighttextcolor.png"]];
roomratetxt.backgroundColor = [UIColor clearColor];
roomratetxt.font = [UIFont systemFontOfSize:12];
roomratetxt.text = [NSString stringWithFormat:#"%#",[myarray objectAtIndex:i]];
roomratetxt.textAlignment = NSTextAlignmentRight;
[roomratetxt setTag:i];
[roomratetxt setDelegate:(id)self];
[scrlsummery addSubview:roomratetxt];
}
}
i want to make all 5 textfields in editable mode. but as of now, the last textfield is only in editing mode and the rest all are non editable mode.
Can anyone plz suggest me some ideas ?How to achieve this
Thanks in advance.
Ajeet Kumar
First of all you need to provide different frames for that you can them in different position. Your above code looks correct and it must be in editable mode. I execute below snippet on my project and it works like a charm. I am assuming you are using Scrollview and added all textfield in it. Only thing make sure you are not disabling them from
(BOOL)textFieldShouldBeginEditing:(UITextField *)textField; // return NO to disallow editing.
or
(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string; // return NO to not change
text
for (int i = 0; [myarray count]; i ++){
roomratetxt = [[UITextField alloc]init];
roomratetxt.frame = CGRectMake(200, i*20, 90, 20);
roomratetxt.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"lighttextcolor.png"]];
roomratetxt.backgroundColor = [UIColor clearColor];
roomratetxt.font = [UIFont systemFontOfSize:12];
roomratetxt.text = [NSString stringWithFormat:#"%#",[myarray objectAtIndex:i]];
roomratetxt.textAlignment = NSTextAlignmentRight;
[roomratetxt setTag:i];
[roomratetxt setDelegate:(id)self];
[scrlsummery addSubview:roomratetxt];
}
-(void)createDynamic_textfld{
UITextField *roomratetxt;
UIScrollView *scrlsummery;
NSMutableArray *myarray = [NSMutableArray arrayWithObjects:#[#"one",#"two",#"three",#"four",#"five"], nil];
for (int i = 0; [myarray count]; i ++){
roomratetxt = [[UITextField alloc]init];
roomratetxt.frame = CGRectMake(200, i*0, 90, 20);
roomratetxt.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"lighttextcolor.png"]];
roomratetxt.backgroundColor = [UIColor clearColor];
roomratetxt.font = [UIFont systemFontOfSize:12];
roomratetxt.text = [NSString stringWithFormat:#"%#",[myarray objectAtIndex:i]];
roomratetxt.textAlignment = NSTextAlignmentRight;
[roomratetxt setTag:i];
[roomratetxt setDelegate:(id)self];
[scrlsummery addSubview:roomratetxt];
}
}
The frame of all 5 textField are putting in the same position. You might need to change their frame as well.
for (int i = 0; [myarray count]; i ++){
roomratetxt = [[UITextField alloc] init];
roomratetxt.frame = CGRectMake(200, i*60, 90, 20);
roomratetxt.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"lighttextcolor.png"]];
roomratetxt.backgroundColor = [UIColor clearColor];
roomratetxt.font = [UIFont systemFontOfSize:12];
roomratetxt.text = [NSString stringWithFormat:#"%#",[myarray objectAtIndex:i]];
roomratetxt.textAlignment = NSTextAlignmentRight;
[roomratetxt setTag:i];
[roomratetxt setDelegate:(id)self];
[scrlsummery addSubview:roomratetxt];
}

Access text values from dynamically created UITextFields. iOS

I am creating UITextField 's in my view based on the count of an NSArray.
I want to know how I can access the text values based on the tag of the UITextField in my NSArray.
So after I add the below UITextField 's to my view how would I write code to retrieve .text values for myTextfield0, myTextfield1 and myTextfield2 respectively?
Example:
NSString *textFeildTextString = [NSString stringWithFormat:#"%#",myTextfield1.text];
Actual Code:
self.textFieldArray = [NSArray arrayWithObjects:#"one", #"two", #"three",nil];
NSMutableDictionary *myDict = [NSMutableDictionary dictionary];
for (int i=0; i<[self.textFieldArray count]; i++) {
UIView *spacerView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
UITextField *myTextField = [[UITextField alloc]initWithFrame:CGRectMake(20, 60*i+150, 280, 45)];
myTextField.borderStyle = UITextBorderStyleNone;
myTextField.font = [UIFont systemFontOfSize:14];
myTextField.returnKeyType = UIReturnKeyDefault;
myTextField.placeholder = NSLocalizedString(#"Answer", nil);
myTextField.inputAccessoryView = [super createInputToolbar];
myTextField.background = [UIImage imageNamed:#"TextFieldBg"];
myTextField.textColor = [UIColor appTextColorGrey];
[myTextField setLeftView: spacerView1];
myTextField.leftViewMode = UITextFieldViewModeAlways;
myTextField.delegate = self;
myTextField.tag = 200+i;
[myDict setObject:myTextField forKey:[NSString stringWithFormat:#"myTextfield%d", i]];
[self.view addSubview:myTextField];
}
NSLog(#"Dict: %#",myDict);
The NSlog of my UITexfields
2014-10-31 11:58:32.715 [51992:13536821] Dict: {
myTextfield0 = "<UITextField: 0x7faea14f8430; frame = (20 150; 280 45); text = ''; clipsToBounds = YES; opaque = NO; tag = 200; layer = <CALayer: 0x7faea14f82d0>>";
myTextfield1 = "<UITextField: 0x7faea14fae70; frame = (20 210; 280 45); text = ''; clipsToBounds = YES; opaque = NO; tag = 201; layer = <CALayer: 0x7faea14faca0>>";
myTextfield2 = "<UITextField: 0x7faea16dce30; frame = (20 270; 280 45); text = ''; clipsToBounds = YES; opaque = NO; tag = 202; layer = <CALayer: 0x7faea16d19c0>>";
}
for (int i=0; i<[self.textFieldArray count]; i++) {
UITextField *txt = (UITextField *)[myDict objectForKey:[NSString stringWithFormat:#"myTextfield%d", i]];
NSLog(#"Text %#",txt.text);
}
You can access them either by their tag :
UITextField *textField= (UITextField *)[self.view viewWithTag:200]; // Your first text field (201 your second etc..)
NSString *text = textField.text;
Or access them directly via your dictionary as you already know the key for each one of them:
UITextField *textField = (UITextField *)[myDict objectForKey:#"myTextField0"];
Note that in order for the dictionary to stay around declare a strong property member in your class and assign it to the created local dictionary (otherwise it will be lost by ARC) so at the end of the method you will have something like:
self.myDict = myDict;

Insert NSArray of strings into UILabel and count by 1.

How Would I insert an array of strings into UILabel, and have them load or count by 1?
I'm trying to load the following array into the UILabel:
self.array = [NSArray arrayWithObjects:#"Testing 1",#"Testing 2",#"Testing 3", nil];
Here I am using an UIScrollView that automatically changes from each slide to each slide:
for (int i=1; i<=3; i++) {
// create label
UILabel *text = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,30)];
text.text = [NSString stringWithFormat:#"%#", self.array];
text.font=[UIFont fontWithName:#"HelveticaNeueLTStd-LtCn" size:15];
text.textColor = [UIColor darkGrayColor];
text.textAlignment =NSTextAlignmentCenter;
// create imageView
UIImageView *lblView = [[UIImageView alloc] initWithFrame:CGRectMake((i-1)*scrMain.frame.size.width, 325, 280, 240)];
// set label
[lblView addSubview:text];
// apply tag to access in future
lblView.tag=i+1;
// add to scrollView
[scrMain addSubview:lblView];
}
I have an example of how to do it with UIImageView:
for (int i=1; i<=3; i++) {
// create image
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:#"sti%02i.png",i]];
// create imageView
UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake((i-1)*scrMain.frame.size.width + 23, 60, 280, 260)];
// set scale to fill
imgV.contentMode=UIViewContentModeScaleToFill;
// set image
[imgV setImage:image];
// apply tag to access in future
imgV.tag=i+1;
// add to scrollView
[scrMain addSubview:imgV];
}
The images are in my project and are numbered sti01, sti02, and so on... It then counts by one for each images and then loads them into the scrollview. I hope this helps!
The y-position of the label should be adjusted according to the index.
You can use the array count instead of a fixed '3'.
You don't need an UIImageView in between.
You can try this:
for (int i = 0; i < self.array.count; i++) {
// create label
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, i*30, self.view.frame.size.width,30)];
label.text = [self.array objectAtIndex:i];
label.font = [UIFont fontWithName:#"HelveticaNeueLTStd-LtCn" size:15];
label.textColor = [UIColor darkGrayColor];
label.textAlignment = NSTextAlignmentCenter;
// add to scrollView
[scrMain addSubview:label];
}
If I'm understanding you correctly, you need to make the following change:
text.text = [NSString stringWithFormat:#"%#", [self.array objectAtIndex:i]];
This will pull out the ith object from your array of strings and set that as the text of your UILabel.
Why don't you loop through the array instead of trying to assign the text to the whole array like this:
for (int i=0; i<3; i++) {
// create label
UILabel *text = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,30)];
text.text = [NSString stringWithFormat:#"%#", [self.array objectAtIndex:i]];
text.font=[UIFont fontWithName:#"HelveticaNeueLTStd-LtCn" size:15];
text.textColor = [UIColor darkGrayColor];
text.textAlignment =NSTextAlignmentCenter;
// create imageView
UIImageView *lblView = [[UIImageView alloc] initWithFrame:CGRectMake((i-1)*scrMain.frame.size.width, 325, 280, 240)];
// set label
[lblView addSubview:text];
// apply tag to access in future
lblView.tag=i+1;
// add to scrollView
[scrMain addSubview:lblView];
}
That way you're just pulling that one string out, assigning it as the UILabel's text, then adding it as a subview to the appropriate imageView.

Resources