How to delete UITextfield and entered data from it in iOS - 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.

Related

Custom UIAlertView not resizing for keyboard after its 1st appearance

I have a custom UIAlertVIew with 2 textFields that I am using to input values into. The first time that the customUIAlertVIew is displayed, the view is moved up to make room for the keyboard.
This is unfortunately, not the case for each subsequent display. Each subsequent time, the alertView isn't moved up for the keyboard.
I am looking for what is causing this problem, and how can I get around it in the future.
EDIT: Here is the code for how the custom UIAlertVIew is created.
CustomUIAlertView.m
-(id)initWithTitle:(NSString *)title {
if (self = [super init]){
self.title = title;
self.message = #"\n\n\n\n\n\n";
[self addButtonWithTitle:#"Cancel"];
[self addButtonWithTitle:#"Done"];
[self setDelegate:self];
}
return self;
}
-(void)didPresentAlertView:(UIAlertView *)alertView{
NSArray *subViews = [UIApplication sharedApplication].keyWindow.rootViewController.
presentedViewController.view.subviews;
if (subViews.count >1){
UIView *presentedView = [subViews objectAtIndex:1];
UILabel *player1Label = [[UILabel alloc]initWithFrame:CGRectMake(20, 55, 130, 21)];
player1Label.text = [NSString stringWithFormat:#"Player 1 Score"];
// player1Label.textInputMode = UIKeyboardTypeNumberPad;
player1Label.tag = 42;
[presentedView addSubview:player1Label];
UILabel *player2Label = [[UILabel alloc]initWithFrame:CGRectMake(20, 75, 130, 21)];
player2Label.text = [NSString stringWithFormat:#"player 2 Score"];
player2Label.tag = 43;
[presentedView addSubview:player2Label];
self.p1ScoreField = [[UITextField alloc]initWithFrame:CGRectMake(150, 55, 80, 21)];
self.p1ScoreField.placeholder= #"score";
self.p1ScoreField.tag = 44;
self.p1ScoreField.keyboardType = UIKeyboardTypeNumberPad;
self.p1ScoreField.borderStyle = UITextBorderStyleRoundedRect;
self.p1ScoreField.delegate = self;
[self.p1ScoreField addTarget:self action:#selector(UITextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
[presentedView addSubview:self.p1ScoreField];
self.p2ScoreField = [[UITextField alloc]initWithFrame:CGRectMake(150, 75, 80, 21)];
self.p2ScoreField.tag = 45;
self.p2ScoreField.placeholder = #"score";
self.p2ScoreField.keyboardType = UIKeyboardTypeNumberPad;
self.p2ScoreField.borderStyle = UITextBorderStyleRoundedRect;
self.p2ScoreField.delegate = self;
[self.p2ScoreField addTarget:self action:#selector(UITextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
[presentedView addSubview:self.p2ScoreField];
}
}
View presented in a separate view Controller. Alloc/Init is called on alertView at the viewDidAppear method.
- (IBAction)addNewRoundButtonPressed:(id)sender {
[alertView show];
}
Adding subviews to UIAlertView is not supported by Apple and is strongly discouraged.
You're better off using a regular view controller with custom modal presentation (look up UIViewControllerAnimatedTransitioning) or Googling a 3rd-party replacement.

Why does UISearchBar's UITextField not respond like a normal UITextField to a rightview?

I'm having trouble implementing a UISearchBar whose UITextField has a rightview. I tried on a normal UITextField the following:
self.textField = [[UITextField alloc] initWithFrame: CGRectMake(10, 30, 300, 30)];
self.textField.borderStyle = UITextBorderStyleRoundedRect;
self.textField.clearButtonMode = UITextFieldViewModeNever;
self.textField.delegate = self;
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, 150, 44)];
[button setBackgroundColor: [UIColor redColor]];
[self.textField setRightViewMode:UITextFieldViewModeAlways];
[self.textField setRightView:button];
[self.view addSubview:self.textField];
And as expected, it generates the following:
I need the UISearchBar's UITextField to be have the same -- so I decided to subclass UISearchBar.
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// This is simply here to make sure that we are able to get the textfield
[self setSearchTextPositionAdjustment:UIOffsetMake(0, 0)];
// Function that helps us get the textfield
UITextField *textField = [self textFieldGetter];
// This will be true if we call setSearchTextFieldPositionAdjust
if (textField) {
// Verify that the textfield exists...
NSLog(#"The textField does exist");
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, 150, 44)];
[button setBackgroundColor: [UIColor redColor]];
// Set the clear button to be off
textField.clearButtonMode = UITextFieldViewModeNever;
// Make the button the rightview of the textfield
[textField setRightView:button];
[textField setRightViewMode:UITextFieldViewModeAlways];
}
}
return self;
}
But it does not work and the UISearchBar simply looks like:
The UITextFieldGetter is in essence something very similar to this answer.
Why isn't the UITextField the same in the UISearchBar as it is normally? Is there a way that I can get the same effect programmatically? Or if it can't be done, is there a way that I can change the UITextField's width once I know the button is there?

Adding multiple text fields with the same code

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

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