Getting TextField Text On Button Click - ios

I am developing an IOS App. I am creating a text field and a button dynamically, and I want to get textfield's text on button click, but I'm getting an error:
[UIView setText:]: unrecognized selector sent to instance
Here is my code:
- (IBAction)customFieldAdd:(id)sender{
[_addfieldArray addObject:_field];
x = 10;
y = 10;
for( int i = 0; i < [_addfieldArray count]; i++ ) {
UITextField *copyfield = [[UITextField alloc]initWithFrame:CGRectMake(5.0, x + _field.frame.size.height, 195.0f, 30.0f)];
[copyfield setDelegate:self];
[copyfield setTag:i];
[_filterPossibleValueView addSubview:copyfield];
x = x+_field.frame.size.height+10;
UIButton *copyAddButton = [[UIButton alloc]initWithFrame:CGRectMake(202.0f, y + _addField.frame.size.height, 30.0f, 30.0f)];
[copyAddButton setTag:i];
[copyAddButton addTarget:self action:#selector(customFieldDelete:) forControlEvents:UIControlEventTouchUpInside];
[_filterPossibleValueView addSubview:copyAddButton];
y = y+_addField.frame.size.height+10;
count++;
}
}
- (IBAction)customFieldDelete:(id)sender{
UIButton *button = (UIButton*)sender;
NSInteger index = button.tag;
// [_addfieldArray removeObjectAtIndex:index];
UITextField *field = [_filterPossibleValueView viewWithTag:index];
NSString *myText = field.text;
}

The default value for the tag property is 0, and you are setting that value to one of the text fields. So, when you try to get the view with tag == 0, it will have more than one view with that tag.
You should use an offset when setting the tag:
[copyfield setTag:kOffset + i];
...
[copyAddButton setTag:kOffset*2 + i]; // note that the button and the text field should not have the same tag either
where kOffset is defined (for example) like this:
let kOffset: Int = 1000
Then, to get the text field's text, you can use:
NSInteger tag = button.tag - kOffset;
UITextField *field = [_filterPossibleValueView viewWithTag:tag];
NSString *myText = field.text;

Related

Showing Selected Buttons if Back button is Pressed [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
On first Page i am having some buttons , if i press any button it will move to Second page , here if i press back button in the navigation bar it will move to first page
i have created the buttons dynamically based on the array count ,i want to show the selected button when i move back to first page , how can i do this ?Please help me to do this .here is the code that i have used for creating buttons
int buttonheight = 30;
int horizontalPadding = 20;
int verticalPadding = 20;
int totalwidth = self.view.frame.size.width;
int x = 10;
int y = 150;
for (int i=0; i<array.count; i++)
{
NSString* titre = [array objectAtIndex:i];
//
CGSize contstrainedSize = CGSizeMake(200, 40);//The maximum width and height
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:20.0], NSFontAttributeName,
nil];
CGRect frame = [titre boundingRectWithSize:contstrainedSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDictionary context:nil];
int xpos = x + CGRectGetWidth(frame);
if (xpos > totalwidth) {
y =y +buttonheight+ verticalPadding;
x = 10;
}
UIButton * word= [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.word = word;
NSLog(#"%#", NSStringFromCGRect(frame));
word = [UIButton buttonWithType:UIButtonTypeRoundedRect];
word.frame = CGRectMake(x, y, CGRectGetWidth(frame)+5, CGRectGetHeight(frame));
[word setTitle:titre forState:UIControlStateNormal];
word.backgroundColor = [UIColor colorWithRed:30.0/255.0 green:134.0/255.0 blue:255.0/255.0 alpha:1.0];
[word setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[word setTag:i];
[word addTarget:self action:#selector(btn1Tapped:) forControlEvents:UIControlEventTouchUpInside];
word.layer.borderColor = [UIColor blackColor].CGColor;
word.layer.borderWidth = 1.0f;
word.layer.cornerRadius = 5;
[self.view addSubview:word];
x =x+horizontalPadding+CGRectGetWidth(frame);
}
- (IBAction)btn1Tapped:(id)sender {
NSString *btnTitle;
btnTitle = [(UIButton *)sender currentTitle];
NSLog(#"%#",self.title);
ReasonViewController *ReasonVC = [self.storyboard instantiateViewControllerWithIdentifier:#"ReasonVC"];
ReasonVC.btnTitle = btnTitle;
NSLog(#"%#",self.imageArray);
ReasonVC.imageArray1 = self.imageArray;
[self.navigationController pushViewController:ReasonVC animated:YES];
}
=====Appdelegate.h========
#property (assign, nonatomic) long int btnTag;
=======CategoryViewController.h============
import "AppDelegate.h"
#interface CategoryViewController : UIViewController
{
AppDelegate *appdel;
}
===========CategoryViewController.m=======
add code
if(appdel.btnTag == word.tag)
{
word.selected = YES;
}
below [word setTag:i]; code
then add
UIButton *btn = (UIButton *) sender;
appdel.btnTag = btn.tag;
in - (IBAction)btn1Tapped:(id)sender method
The UIButton object has different states included the "Selected state". You can set different background image or title for each state you want. When you press it you can change its state like this:
//After you inited your UIButton Object do this:
[button setBackgroundImage:selectedBGImage forState:UIControlStateSelected];
[button setBackgroundImage:deselectedBGImage forState:UIControlStateNormal];
//You can also find the title change method for state accordingly
- (void)buttonAction:(UIButton *)sender
{
sender.selected = !sender.selected;
//TODO
}
So, when you pop back, the button will keep its "selected" state.
You have to store button tag in appdelegate and while creating button check with button tag/i values and do selected. please see below code
in AppDelegate.h
#property (assign, nonatomic) int btnTag;
create an object of AppDelegate on your current ViewController then
AppDelegate *appdel = (AppDelegate *)[[UIApplication sharedApplication] delegate];
int buttonheight = 30;
.
.
.
[word setTag:i];
if(word.tag == appdel.btnTag)//appdel is object of AppDelegate
{
word.selected = YES;
}
[word addTarget:self action:#selector(btn1Tapped:) forControlEvents:UIControlEventTouchUpInside];
word.layer.borderColor = [UIColor blackColor].CGColor;
word.layer.borderWidth = 1.0f;
word.layer.cornerRadius = 5;
[self.view addSubview:word];
x =x+horizontalPadding+CGRectGetWidth(frame);
}
- (IBAction)btn1Tapped:(id)sender {
UIButton *btn = (UIButton *) sender;
appdel.btnTag = btn.tag;
NSString *btnTitle;
btnTitle = [(UIButton *)sender currentTitle];
NSLog(#"%#",self.title);
ReasonViewController *ReasonVC = [self.storyboard instantiateViewControllerWithIdentifier:#"ReasonVC"];
ReasonVC.btnTitle = btnTitle;
NSLog(#"%#",self.imageArray);
ReasonVC.imageArray1 = self.imageArray;
[self.navigationController pushViewController:ReasonVC animated:YES];
}
enter image description here
I am getting like below screenshot , if i tapped any button it will move to next page and the backgroundcolor is changed to red color,and come back to same page by clicking back and now i tapped another button it is also showing in red color.
I have use this two lines in button action method :
UIButton *btn = (UIButton *) sender;
[btn setBackgroundColor:[UIColor redColor]];

How to create dynamic textfield , accessble and editable for each textfield in iOS

Can anyone help me ? I want to create dynamic text field in side a loop.I have been able to create and made it editable too. My requirements are in below.
i.I want to access each text fields value and make a sum of those will store in a Label.
ii. Let's say there are 5 dynamic created text fields having value (10,20,30,40,50).
so label displays sum of 5 value. ie. 10+20+30+40+50 = 150
if i make changes in either textfield values, it should recalculate and changes the total sum in label.
my logic goes as below.
-(void)create
{
myarr = [NSMutableArray arrayWithObjects:#"1000",#"2000",#"3000",#"4000",#"5000", nil];
int x = 20, y = 50;
int width = 280, height = 40;
for (int item=0; item<[myarr count]; item++)
{
edit_txt = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
edit_txt.text = [NSString stringWithFormat:#"%#",[myarr objectAtIndex:item]];
[edit_txt setTag:item+1];
edit_txt.placeholder = #"Click here to type";
edit_txt.borderStyle = UITextBorderStyleRoundedRect;
edit_txt.font = [UIFont systemFontOfSize:15];
edit_txt.textAlignment = NSTextAlignmentLeft;
edit_txt.returnKeyType = UIReturnKeyDefault;
edit_txt.delegate = (id)self;
[self.view addSubview:edit_txt];
y += height;
}
tot_txt = [[UITextField alloc]initWithFrame:CGRectMake(edit_txt.frame.origin.x, edit_txt.frame.origin.y + height + 10, width , height)];
tot_txt.placeholder = #"Total Value";
tot_txt.borderStyle = UITextBorderStyleRoundedRect;
tot_txt.font = [UIFont systemFontOfSize:15];
tot_txt.textAlignment = NSTextAlignmentLeft;
tot_txt.returnKeyType = UIReturnKeyDefault;
tot_txt.delegate = (id)self;
[self.view addSubview:tot_txt];
save_btn = [UIButton buttonWithType:UIButtonTypeCustom];
[save_btn setFrame:CGRectMake(tot_txt.frame.origin.x, tot_txt.frame.origin.y + height + 10, width , height)];
[save_btn setTitle:#"Save" forState:UIControlStateNormal];
[save_btn addTarget:self action:#selector(save_click:) forControlEvents:UIControlEventTouchUpInside];
[save_btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[self.view addSubview:save_btn];
CALayer *btnlayer = [save_btn layer];
[btnlayer setBorderColor:[UIColor redColor].CGColor];
[btnlayer setBorderWidth:0.3];
[btnlayer setCornerRadius:20.0];
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
int count = 0;
for (int item = 0; item < [myarr count]; item++)
{
UITextField *textField = ([[self.view viewWithTag:item + 1] isKindOfClass:[UITextField class]])?(UITextField *)[self.view viewWithTag:item + 1]:nil;
count += [textField.text intValue];
}
tot_txt.text = [NSString stringWithFormat:#"%d", count];
}
Thanks in advance.
Ajeet Kumar.
It would be more easy,
To access each text field (the scope is available only within the loop),you can use tag property of the text field.
Example:
for (int itemIndex = 1; itemIndex <= 5; itemIndex++)
{
UITextField *textField = [[UITextField alloc] initWithFrame:yourFrame];
//all properties assigning here
textField.tag = itemIndex; //assigning tag here(starts from 1).
textField.delegate = self;
[self.view addSubview: textField];
}
Now, here comes the calculation. Implement the UITextField delegates.
Write the <UITextFieldDelegate> in your .h file
#interface yourClassName : UIViewController <UITextFieldDelegate>
To calculate while end editing,
-(void)textFieldDidEndEditing:(UITextField *)textField
{
int count = 0;
for (int itemIndex = 1; itemIndex <= 5; itemIndex++)
{
UITextField *textField = ([[self.view viewWithTag:itemIndex] isKindOfClass:[UITextField class]])?(UITextField *)[self.view viewWithTag:itemIndex]:nil;
count += [textField.text intValue];
}
countLabel.text = [NSString stringWithFormat:#"%d", count];
}
To calculate while editing, implement delegate shouldChangeCharactersInRange and use the same code base.
Also implement the delegates textFieldShouldClear ,
textFieldShouldReturn and use the same code base.
Please make sure that, your view not holding any elements with the tag from 1 to 5 except these test fields.
Also, you can avoid the looping by applying your thoughts on it ;)
I did like this,
#import "ViewController.h"
#interface ViewController () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate> {
UITableView* _tableView;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 100, 768, 600) style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
[self.view addSubview:_tableView];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
return 5;
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:#"SomeCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"SomeCell"];
UITextField* _textField = [[UITextField alloc] initWithFrame:CGRectMake(5, 5, 600, 40)];
_textField.delegate = self;
_textField.tag = indexPath.row + 1;
[_textField setBackgroundColor:[UIColor lightGrayColor]];
[_textField addTarget:self action:#selector(onTextChange:) forControlEvents:UIControlEventEditingChanged];
[cell.contentView addSubview:_textField];
}
return cell;
}
- (void)onTextChange:(id)sender
{
double result = 0.0;
for (int itemIndex = 0; itemIndex < 5; itemIndex++) {
UITableViewCell* cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:itemIndex inSection:0]];
UITextField* fooTF = (UITextField*)[cell.contentView viewWithTag:itemIndex + 1];
result += [fooTF.text doubleValue];
}
// update your lable here
NSLog(#"result %f", result);
//for sample
self.title = [NSString stringWithFormat:#"%f", result];
}
- (float)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
return 50.0;
}
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string
{
NSNumberFormatter* nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle:NSNumberFormatterNoStyle];
NSString* newString = [NSString stringWithFormat:#"%#%#", textField.text, string];
NSNumber* number = [nf numberFromString:newString];
//allow only numbers
if (number)
return YES;
else
return NO;
}

Targeting programmatically created UIButton

Question: How do I target one of many dynamically created UIButtons so I can change its properties?
Background: I have a storyboard with a UIViewConroller. When this UIVC loads a UIScrollView is added, to which a UIImageView is placed that has an exhibition floor plan. Each exhibitor has an entry in a database that contains its location on the floor plan. When the UIVC is loaded a loop is run for all exhibitors and each one has a UIButton drawn on the UIIV. When a UIB is clicked the button background colour is changed (to confirm which exhibitor has been selected) and a UIAlertView is shown with information about that exhibitor. When the UIAV's 'cancel' (ok) button is pressed the UIAV closes and the background highlight colour that was applied previously should be removed but here is where I am having the problem. I am unable to target the UIButton so I can change its background colour.
What I have tried so far: As each button is created I am giving it a tag and a title and recording both in an array. When the 'cancel' button is pressed on the UIAlertView I have tried checking the tag in the array but I still cannot actually target the UIButton.
I was thinking something like this:
// obviously not correct syntax but the kind of thing I want
[exhibitorBtn(tag) setBackgroundColor:[UIColor greenColor]];
So, say I have 12 UIButtons all called exhibitorBtn but with different titles and tags:
Object ----- Name ---------- Title -------- Tag
UIButton -- exhibitorBtn -- Glaxo ------ 1
UIButton -- exhibitorBtn -- Porsche --- 2
UIButton -- exhibitorBtn -- Rolex ------- 3 < How would I target that button's properties?
Edit - added the code that creates the buttons just to clarify:
for (NSDictionary *dict in exhibitorStandArray) {
NSInteger currentPosition = [exhibitorStandArray indexOfObject:dict];
NSLog(#"Position in array = %li", (long)currentPosition);
if (![dict[#"locCoords"] isEqual: #""]) {
NSInteger buttonTag = [exhibitorStandArray indexOfObject:dict];
NSString *standNo = dict[#"locStandNo"];
NSMutableDictionary *buttonDictionary = [[NSMutableDictionary alloc] init];
[buttonDictionary setObject:[NSNumber numberWithInteger:buttonTag] forKey:#"buttonTag"];
[buttonDictionary setObject:standNo forKey:#"buttonStandNo"];
[_masterButtonList addObject:buttonDictionary];
NSString *locCoords = dict[#"locCoords"];
NSArray *tempArray =[locCoords componentsSeparatedByString:#","];
tlcTop = [[tempArray objectAtIndex:0] integerValue];
tlcLeft = [[tempArray objectAtIndex:1] integerValue];
brcTop = [[tempArray objectAtIndex:2] integerValue];
brcRight = [[tempArray objectAtIndex:3] integerValue];
buttonWidth = brcRight - tlcLeft;
buttonHeight = brcTop - tlcTop;
testBtn = [UIButton buttonWithType:UIButtonTypeCustom];
testBtn.frame = CGRectMake(tlcTop, tlcLeft, buttonHeight, buttonWidth);
testBtn.titleLabel.text = standNo;
testBtn.tag = buttonTag;
NSLog(#"UIButton Title = %#", testBtn.titleLabel.text);
NSLog(#"UIButton Tag = %li", (long)testBtn.tag);
testBtn.titleLabel.hidden = YES;
[testBtn addTarget:self action:#selector(displayInfo:) forControlEvents:UIControlEventTouchUpInside];
[_buttonArray addObject:testBtn];
[_imageView addSubview:testBtn];
}
}
Why can't you just use viewWithTag:
UIButton * button = (UIButton *)[self.scrollView viewWithTag:tag];
Your code probably looks something like this:
for (int i = 0; i < 5; i++)
{
UIButton *exhibitorBtn = [[UIButton alloc] initWithFrame:etc..];
exhibitorButton.tag = i;
[scrollView addSubview:exhibitorBtn];
}
Just change the loop so every button will be added to an array, too. Declare a NSMutableArray as a property: #property (strong, nonatomic) NSMutableArray *buttonsArray;
And #synthesize and initialise it in your init method. buttonsArray = [[NSMutableArray alloc] init]
Then, change the loop like I said above:
for (int i = 0; i < 5; i++)
{
UIButton *exhibitorBtn = [[UIButton alloc] initWithFrame:etc..];
exhibitorButton.tag = i;
[buttonsArray addObject:exhibitorBtn];
[scrollView addSubview:exhibitorBtn];
}
Finally, when you want to access the buttons:
for (int i = 0; i < [buttonsArray count]; i++)
{
UIButton *button = [buttonsArray objectAtIndex:i];
if (button.tag == 3) { // This is the button you wanted to target!
[button setHidden:YES];
}
}
Let's make it clear: you did set target and action of UIButton to controller's IBAction method and get the button as sender argument. Now you show UIAlertView and after it is dismissed, you want to send some message to that button, right?
Another method is to set delegate property for UIAlertView and respond to – alertView:clickedButtonAtIndex: delegate method. Trouble is that sender is lost at that point. You may use objc_setAssociatedObject to associate UIButton with UIAlertView and the retrieve it back when delegate method fires:
#import <objc/runtime.h>
static char myButtonKey = 0; // to use address as a key (value is irrelevant)
- (IBAction)buttonDidClick:(id)button
{
UIAlertView *alertView = <setup alert>;
[alertView setDelegate:self];
objc_setAssociatedObject(alertView, &myButtonKey, button, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
<show alert>;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
UIButton *thatButton = objc_getAssociatedObject(alertView, &myButtonKey);
<use thatButton>;
}
Try to create button in this way and add selector to them :
for (int i = 0; i < 5; i++)
{
UIButton *button = [[UIButton alloc] initWithFrame:CGRectZero];
button.tag = i;
[button addTarget:self
action:#selector(buttonPressedMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Show View" forState:UIControlStateNormal];
// add button to subview here
}
In method, just do whatever, you want to do :
- (void) buttonPressedMethod : (id) sender {
UIButton *selectedButton = (UIButton *)sender;
if (selectedButton.tag == 0) {
}
else if (selectedButton.tag == 1) {
}
else {
}
}

Unable to replace the tags of UIButton(s)

I have say for example 7 UIButtons namely c1 to c7. Now I have assigned tags starting from 1 to 7 respectively for the UIButtons c1 to c7.
Now when I select c2 for example it is removed from superView so now the tag for c2 which was 2 is transferred to c3 , 3 to c4 and so on.
This is what I have tried but logic is not working properly. I have posted question with similar concern before but didn't get any proper response.
-(void)totesttheFunction
{
for(int i=0; i<7; i++)
{
UIButton *testHere = (UIButton*)[self.view viewWithTag:i];
if([testHere isSelected])
{
int backuptagFor = testHere.tag;
CGFloat diff = 30.0;
for(int j=i+1; j<7;j++)
{
UIButton *btnToReplace = (UIButton*)[self.view viewWithTag:j];
CGRect setRect = CGRectMake(btnToReplace.frame.origin.x-diff, btnToReplace.frame.origin.y, btnToReplace.frame.size.width, btnToReplace.frame.size.height);
btnToReplace.tag = backuptagFor;
[testHere removeFromSuperview];
}
}
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
for(int itemIndex = 1; itemIndex <= 7; itemIndex++)
{
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(itemIndex*40, 10, 30, 30)];
btn.tag = itemIndex;
[self.view addSubview:btn];
if (itemIndex == 3 ||itemIndex == 4)
{
[btn setSelected:YES];
}
}
[self testFunction];
}
- (void)testFunction
{
int totalButtons = 7;
int totalRemovedButtons = 0;
for(int itemIndex = 1; itemIndex <= totalButtons; itemIndex++)
{
UIButton *testHere = ([[self.view viewWithTag:itemIndex] isKindOfClass:[UIButton class]])?(UIButton *)[self.view viewWithTag:itemIndex]:nil;
if([testHere isSelected])
{
[testHere removeFromSuperview];
NSLog(#"removed button with tag:%d",itemIndex + totalRemovedButtons);
for (int tempItemIndx = itemIndex + 1; tempItemIndx <= totalButtons; tempItemIndx++)
{
UIButton *nextButton = ([[self.view viewWithTag:tempItemIndx] isKindOfClass:[UIButton class]])?(UIButton *)[self.view viewWithTag:tempItemIndx]:nil;
nextButton.tag = tempItemIndx - 1;
}
itemIndex--;
totalRemovedButtons ++;
}
NSLog(#"loop run %d",itemIndex);
}
NSLog(#"-------------------------------------------------------------------");
//Checking the updated tags.
for(int itemIndex = 1; itemIndex <= (totalButtons - totalRemovedButtons); itemIndex++)
{
UIButton *testHere = ([[self.view viewWithTag:itemIndex] isKindOfClass:[UIButton class]])?(UIButton *)[self.view viewWithTag:itemIndex]:nil;
NSLog(#"New tags %d",testHere.tag);
}
}
Output:
loop run 1
loop run 2
removed button with tag:3
loop run 2
removed button with tag:4
loop run 2
loop run 3
loop run 4
loop run 5
loop run 6
loop run 7
---------------------
New tags 1
New tags 2
New tags 3
New tags 4
New tags 5
Apply below approach first delete old UI and re-generate new UI from scratch assign them same tags again
e.g. 123456 - No 4 deleted - 12356 - store remaining data - re-generate new UI from old data
now 12345
- (IBAction)actionDeletePrevEmp:(UIButton *)sender
{
// ********* DELETED OLD UI AND GENERATED DATA FROM OLD UI **********
NSMutableArray *tempArray = [[NSMutableArray alloc]init];
for (int BTNCounter = 1; BTNCounter < 8 ;BTNCounter++)
{
if (BTNCounter == sender.tag)
{ // do not add contents to array
// delete it from UI
[(UIButton *)[self.view viewWithTag:BTNCounter]removeFromSuperview];
continue;
}
}
// ************* GENERATING NEW UI WITH TEMP DATA **************
int empSizeCounter = 50;
for (int loopCounter = 0, BTNTagCounter = 1 ; BTNTagCounter < 7; loopCounter++)
{
viewPreviousEmployerList = [[UIView alloc]initWithFrame:CGRectMake(0.0, empSizeCounter, 320.0, 50.0)];
// viewPreviousEmployerList.backgroundColor = [UIColor blackColor];
deletePrevEmpButton = [UIButton buttonWithType:UIButtonTypeSystem];
//[deletePrevEmpButton setImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
deletePrevEmpButton = [[UIButton alloc]initWithFrame:CGRectMake(264.0, 10.0, 30.0, 30.0)];
deletePrevEmpButton.backgroundColor = [UIColor blueColor];
deletePrevEmpButton.titleLabel.text = #"X";
deletePrevEmpButton.tag = BTNTagCounter;
if (loopCounter+1 > [tempArray count])
{
btnTemp.text = #"";
}
else
{
btnTemp.text = tempArray[loopCounter];
}
BTNTagCounter++;
[viewPreviousEmployerList addSubview:btnTemp];
[self.viewAddEmployer addSubview:viewPreviousEmployerList];
empSizeCounter = empSizeCounter + 50;
}
First you need to add all button in NSMutableArray and follow me, (here array name is _myArrayOfBtn)
Add button's method such like, (and make sure that each button's have same method name)
[myBuutonName addTarget:self action:#selector(totesttheFunction:) forControlEvents:UIControlEventTouchUpInside];
And method declaration is like,
-(void) totesttheFunction:(UIButton *)sender
{
[sender removeFromSuperview]; // just put this code.
[_myArrayOfBtn removeObjectAtIndex:sender.tag];
// replace tag of buttons
for(int i = 1; i < _myArrayOfBtn.count; i ++)
{
UIButton *btn = (UIButton *)[_myArrayOfBtn objectAtIndex:i]
btn.tag = i;
}
}

How to call a tagged textfield

I am creating a series of textfields programmatically using tags. I want to be able to access the data in each text field, but it keeps reverting back to the last tag.
In this example I am creating 10 textfields. When you click on a field it should turn that field blue, but it always turns the last field blue.
How do I access the field tags so I can get to the correct textfield?
I added NSlog to test the sender #.
#implementation ViewController
#synthesize name = _name ;
- (void)viewDidLoad
{
[super viewDidLoad];
int y = 20 ;
for(int i=1; i <= 10; i++)
{
CGRect frame = CGRectMake(20, y, 100, 30 ) ;
name = [[UITextField alloc] initWithFrame:frame];
[name setTag:i] ;
[name setBackgroundColor:[UIColor whiteColor]] ;
[name addTarget:self action:#selector(makeBlue:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:name];
y += 38;
}
}
- (void)makeBlue:(id)sender
{
int i = (int)[sender tag] ;
[name setTag:i] ;
NSLog(#"%d", i);
[name setBackgroundColor:[UIColor blueColor]] ;
}
EDIT:
That is great. Thank you. It certainly solved one of my problems. I guess I was expecting a different answer that would lead me in a direction to solve my second problem. I want to take the input from a tagged textfield to use it elsewhere. I have the same problem that I am only getting the input from the last textfield.
- (void)viewDidLoad
{
[super viewDidLoad];
int y = 20 ;
for(int tag=1; tag <= 10; tag++)
{
CGRect frame = CGRectMake(20, y, 100, 30 ) ;
name = [[UITextField alloc] initWithFrame:frame];
[name setTag:tag] ;
[name setBackgroundColor:[UIColor whiteColor]] ;
[name addTarget:self action:#selector(makeItSo:) forControlEvents:UIControlEventEditingDidEnd];
[self.view addSubview:name];
[name setDelegate:self] ;
y += 38;
}
}
- (void)makeItSo:(id)sender
{
int tag = (int)[sender tag] ;
[name setTag:tag] ;
NSString * aName = [name text] ;
NSLog(#"%#", aName) ;
}
In this example I don't need to use setTag again in the makeItSo method, but I don't know how to get the value from a particular tag.
In your makeBlue: method you are just re-assigning a tag for no reason. This doesn't change the view. The variable name will point to the last view created in the loop even if you change its tag. If you want to access the views by tag use :
[self.view viewWithTag:<tag>]
So your makeBlue: code will look like:
- (void)makeBlue:(id)sender
{
int tag = (int)[sender tag] ;
UIView *tagView = [self.view viewWithTag:tag]
[tagView setBackgroundColor:[UIColor blueColor]] ;
}
So for taking the value of a text field you would use:
name = [self.view viewWithTag:[sender tag]];
NSString *fieldText = name.text;
NSInteger i = [sender tag];

Resources