Adding multiple text fields with the same code - ios

I want to be able to add between 1 and 20 text fields to my view with the same code.
My idea is to use a for loop and every time add a text field so the first time it loops it adds "textField1" and the second time it adds "textField2" etc.
I'm not sure how I would go about coding this so I'm looking for your help.

Try this code
for 20 textfields you need to take them in UIScrollView .. you can do like this --
UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,0,320,460)];
[scrollView setDelegate:self];
//initialize a textfield array;
NSMutableArray *textFieldArray = [[NSMutableArray alloc]init];
//x, y for first textfield in UIScrollView
float x = 20;
float y = 20;
For(int i=1;i<21;i++)
{
UITextfield *textField = [[UITextfield alloc]initWithFrame:CGRectMake(x,y,200,30)];
textfield.tag = i;
[textField setDelegate:self];
//Add Textfield to array just for futureRefrence
[textFieldArray addObject:textField];
//Add textfield in UIScrollView
[scrollView addSubview:textField];
//Now iterate Y , So they won't over each other
y = y+50;
}
//Now set ScrollView ContentSize
[scrollView setContentSize:CGSizeMake:(320,20*y)];
//Now Finally Add ScrollView in UIView
[self.view addSubView:scrollView];
Also remember declare there delegate in .h file .
and you can access these textfield by the array you put them in ,For Example
If you want a value from textfield three , you can do like this
UITextfield *textfield = (UITextfield *)[textFieldArray objectAtIndex:2];
NSLog(#"text of textField 3 is -- %#",textfield.text);

for (int i = 0; i < 20; i++)
{
UITextField *textField = //setup field
textField.tag = i;
[self.view addSubview:textField];
}
then when you want to reference a field later
UITextField *textField6 = [self.view viewWithTag:6];
UITextField *textField18 = [self.view viewWithTag:18];
etc

NSMutableArray* tfArray = [[NSMutableArray alloc]init];
for (int i = 0; i < 20; i++)
{
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
[self.view addSubview:textField];
[tfArray addObject:textField];
}
if you want to reference a field:
the 6th textfield is for example: (UITextField*)tfArray[5];

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

UITextField does not interact with user when added to a clipped view area

I created a UIView with an outlet named _waypointSubview inside a UIScrollView, which is also inside another UIView, and all 3 were created in my storyboard. From here I am adding UITextFields programmatically, and once there are over 5 UITextFields added it is clipped from the UIScrollView. The UIScrollView and the _waypointSubview are then resized to compensate for the extra UITextField added. The user can then scroll down to see all the UITextFields that were clipped from the view. Only the UITextFields that were clipped do not allow editing. I am not sure why that is. So if I add 10 of them, I cannot edit 6 thru 10. I tried programmatically telling it to enable user interaction using the call [waypointTextField setUserInteractionEnabled:YES];but it did not work.
Can someone please explain why I cannot edit those fields? Thank you.
- (IBAction)addWaypoint:(id)sender {
UITextField *waypointTextField = [[UITextField alloc] initWithFrame:CGRectMake(xCord, yCord, 250, 40)];
waypointTextField.borderStyle = UITextBorderStyleRoundedRect;
waypointTextField.font = [UIFont systemFontOfSize:18];
waypointTextField.placeholder = #"enter waypoint";
waypointTextField.autocorrectionType = UITextAutocorrectionTypeNo;
waypointTextField.keyboardType = UIKeyboardTypeDefault;
waypointTextField.returnKeyType = UIReturnKeyDone;
waypointTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
waypointTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
waypointTextField.delegate = self;
[_waypointSubview addSubview:waypointTextField];
UITextField *commentTextField = [[UITextField alloc] initWithFrame:CGRectMake(xCord + 300, yCord, 380, 40)];
commentTextField.borderStyle = UITextBorderStyleRoundedRect;
commentTextField.font = [UIFont systemFontOfSize:18];
commentTextField.placeholder = #"enter comment";
commentTextField.autocorrectionType = UITextAutocorrectionTypeNo;
commentTextField.keyboardType = UIKeyboardTypeDefault;
commentTextField.returnKeyType = UIReturnKeyDone;
commentTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
commentTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
commentTextField.delegate = self;
[_waypointSubview addSubview:commentTextField];
// if waypointArray is not initialized yet, create and add textfield
if (waypointArray == nil) {
waypointArray = [NSMutableArray arrayWithCapacity:1];
[waypointArray insertObject:waypointTextField atIndex:0];
commentArray = [NSMutableArray arrayWithCapacity:1];
[commentArray insertObject:commentTextField atIndex:0];
}
else{
// check amount of space left in scroll view, and adjust if needed
if ([waypointArray count] > 4) {
self.waypointScrollView.contentSize = CGSizeMake(708, 255 + (([waypointArray count] - 4)*50));
CGRect frame = self.waypointSubview.frame;
frame.size.height += 50;
self.waypointSubview.frame = frame;
//[waypointTextField setUserInteractionEnabled:YES];
}
// add new text fields to corresponding arrays
[waypointArray addObject:waypointTextField];
[commentArray addObject:commentTextField];
}
yCord += 50; // update the yCoordinate that will be used for the next textField placement
}
I am assuming you need to connect _waypointSubview to the view controller on your storyboard by just reading the comments.
In order to do that
Right click on the the view controller icon on the storyboard view controller
Click and drag the little circle to the object you are trying to edit or the method you're trying to implement from the IBAction.
Check your bounds of your textfield as -
UITextField *commentTextField = [[UITextField alloc] initWithFrame:CGRectMake(xCord + 300, yCord, 380, 40)];
Here if you observe the xcordinate, an Iphone has a width of 320points.
If your textfield is 380points wide then how can you accomodate it WHEN its (0,0) is starting from xCord(I dont know what is its value) + 300.
Lower the xcordinate value and color its background, to check whether it falls in bounds as pointed out by #rdelmar

I want my UILabel to follow my UISlider value

I follow the code of user2207904
on viewDidLoad I create 20 sliders and 20 labels
then my 20 labels take the values of my faders (label.text= [NSString stringWithFormat:#"%i", slvalue];)
but like this if I move my labels don't follows my faders values...
how can I do to my labels follows my faders values?
MY CODE
- (void)viewDidLoad
{
[super viewDidLoad];
for(int i=0; i< 20; i++){
//sliders
UISlider *slider = [[[UISlider alloc] initWithFrame:CGRectMake(1+i*50, 450, 300, 10)] autorelease];
slider.minimumValue = 1;
slider.maximumValue = 100;
slider.continuous = YES;
[self.view addSubview:slider];
slider.transform = CGAffineTransformRotate(slider.transform, 270.0/180*M_PI);
[slider setThumbImage:thumbImage0 forState:UIControlStateNormal];
[slider release];
// label
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(1+i*50, 640, 40, 15)];
int slvalue = slider.value;
label.text= [NSString stringWithFormat:#"%i", slvalue];
[self.view addSubview:label];
[label release];
}
New issue :
mofified
I do this :
i put an IBAction in my FirstViewController.m
- (IBAction)sliderUpdate:(UISlider *)sender {
self.label.text = [NSString stringWithFormat:#"%g", sender.value];
}
and put this in my viewDidLoad (FirstViewController.m)
{
[super viewDidLoad];
for(int i=0; i< 20; i++){
//sliders
UISlider *slider = [[[UISlider alloc] initWithFrame:CGRectMake(1+i*50, 450, 300, 10)] autorelease];
slider.minimumValue = 1;
slider.maximumValue = 100;
slider.continuous = YES;
[slider addTarget:self action:#selector(sliderUpdate:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:slider];
slider.transform = CGAffineTransformRotate(slider.transform, 270.0/180*M_PI);
[slider setThumbImage:thumbImage0 forState:UIControlStateNormal];
[slider release];
// label
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(1+i*50, 640, 40, 15)];
int slvalue = slider.value;
label.text= [NSString stringWithFormat:#"%i", slvalue];
[self.view addSubview:label];
[label release];
}
i have this error in my (IBAction)sliderUpdate: Property 'label' not found on object of type 'FirstViewController *'
If you control drag from a slider to the implementation of your UIViewController, it will set up an IBAction method that is called whenever the value is changed. In this method, simply set the text of your label. No need to make a special subclass.
The code will end up looking something like this:
- (IBAction)setLabel:(UISlider *)sender {
self.myLabel.text = [NSString stringWithFormat:#"%g", sender.value];
}
EDIT: It sounds like you are making the sliders programmatically. In that case, you're going to have to call addTarget:action:forControlEvents: on each one to set up the target-action. (The control event will be UIControlEventValueChanged.)
Also, as far as knowing what slider goes to what label, you could make 2 NSArrays in which the ith slider in one array matches the ith label in the other array.
Drag and drop or programetically create one UILabel and UISlider ,then in the Slider use this for slider action
-(IBAction)slider:(id)sender {
NSString *s=[NSString stringWithFormat:#"%f",slider.value];
[label setText:s]; }
So whenever you change your slider your label value also changes.I hope you got it ryt?

How to create dynamic UITextField with different object name?

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

Resources