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];
Related
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;
How to remove the array of UITextField from Scroll Subview, initially when I call API I get some Array Value based on Count I have created Dynamic UITextFiled in My View, But I do know how to remove the Subview
here my sample Code:
// NSArray *strings;
// UIScrollView *scrollView;
// NSMutableArray *textFields;
self.textFields = [NSMutableArray array];
const CGFloat width = 320;
const CGFloat height = 31;
const CGFloat margin = 0;
CGFloat y = 0;
for(NSString *string in strings) {
UITextField *textField = [[UITextField alloc]
initWithFrame:CGRectMake(0, y, width, height)];
textField.delegate = self;
textField.text = string;
[scrollView addSubview:textField];
[textFields addObject:textField];
[textField release];
y += height + margin;
}
scrollView.contentSize = CGSizeMake(width, y - margin);
Firs of all when you are creating this dynamic textField set single tag like 101.
for(NSString *string in strings) {
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, y, width, height)];
textField.delegate = self;
textField.text = string;
//Set tag 101
textField.tag = 101;
[scrollView addSubview:textField];
[textFields addObject:textField];
[textField release];
y += height + margin;
}
Now make one method to remove all this dynamic textFields.
- (void)removeAllDynamicTextFields {
for(UIView *view in scrollView.subViews){
if([view isKindOfClass:[UITextField class]] && view.tag == 101){
[view removeFromSuperview];
}
}
}
}
If you want to remove that textfield from your view then you can simply removi that textfield from your superview.
[yourtextfield removeFromSuperView];
scrollView.subViews.forEach({textField in
if textField is UITextField , textField.tag == XX {
textField.removeFromSuperView()
}
})
Add tag and then remove whatever text view with loop
for (UITextView *i in scrollView){
if([i isKindOfClass:[UITextView class]]){
UITextView *tv = (UITextView *)i;
if(tv.tag == 1){ // Whatever textview want to remove add tag here
/// Write your code
[tv removeFromSuperview];
}
}
}
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;
}
Let me explain my project first. I have some data in my SQLIte DB table called "note".
In "note" table I have these fields: id, noteToken, note.
What I am doing here is load all the note in an NSMUtableArray from that table. And create UIButton according to that array content number and add those buttons in a UIScrollView as subView. The number of buttons and width of scrollview generate auto according to the number of content of that array. Now, when some one tap one of those Buttons, it will bring him to a next viewController and show him the corresponding note details in that viewController.
I do the same thing with another NSMUtableArray, but these time it read all the id from the "note" table. It equally generate new delete button in the same UIScrollView. But if some one tap on these delete button it will delete that particular note from the table "note" of SQLIte DB. AND RELOAD THE UIScrollView. All are done except the RELOAD THE UIScrollView part. This is what I want. I tried with all exist solution but don't know why it's not working.
Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
self.noteToken = [NSString stringWithFormat:#"%#%#", fairId, exibitorId];
scrollViewNoteWidth = 100;
[scrollViewNote setScrollEnabled:YES];
[scrollViewNote setContentSize:CGSizeMake((noteButtonWidth * countNoteButtonArray) + scrollViewNoteWidth, 100)];
sqLite = [[SQLite alloc] init];
[self.sqLite callDataBaseAndNoteTableMethods];
self.noteButtonArrayy = [[NSMutableArray alloc] init];
noteButtonArrayy = [self.sqLite returnDataFromNoteTable:noteToken];
[self LoadNoteButtonAndDeleteButton:noteButtonArrayy];
}
//////////////*----------------------- Note Section (Down) -----------------------*//////////////
-(void) LoadNoteButtonAndDeleteButton:(NSMutableArray *) noteButtonArray
{
sQLiteClass = [[SQLiteClass alloc] init];
noteButtonArrayToShowNoteButton = [[NSMutableArray alloc] init];
/*--------------- Load the noteButton & pass note (Down)---------------*/
for (int i = 0; i < [noteButtonArray count]; i++)
{
sQLiteClass = [noteButtonArray objectAtIndex:i];
// NSString *ids = [NSString stringWithFormat:#"%d", sQLiteClass.idNum];
NSString *nt = sQLiteClass.note;
[noteButtonArrayToShowNoteButton addObject:nt];
}
[self ShowNoteButtonMethod:noteButtonArrayToShowNoteButton];
/*--------------- Load the noteButton & pass note (Up)---------------*/
/*--------------- Load the deleteButton & pass id (Down)---------------*/
noteButtonArrayToDeleteNoteButton = [[NSMutableArray alloc] init];
for (int i = 0; i < [noteButtonArray count]; i++)
{
sQLiteClass = [noteButtonArray objectAtIndex:i];
// Convert int into NSString
NSString *ids = [NSString stringWithFormat:#"%d", sQLiteClass.idNum];
[noteButtonArrayToDeleteNoteButton addObject:ids];
}
[self ShowNoteDeleteButtonMethod:noteButtonArrayToDeleteNoteButton];
/*--------------- Load the deleteButton & pass id (Down)---------------*/
}
-(void) ShowNoteButtonMethod:(NSMutableArray *) btnarray
{
countNoteButtonArray = [btnarray count];
// For note button
noteButtonWidth = 60;
noteButtonXposition = 8;
for (NSString *urls in btnarray)
{
noteButtonXposition = [self addNoteButton:noteButtonXposition AndURL:urls];
}
}
-(int) addNoteButton:(int) xposition AndURL:(NSString *) urls
{
noteButton =[ButtonClass buttonWithType:UIButtonTypeCustom];
noteButton.frame = CGRectMake(noteButtonXposition, 8.0, noteButtonWidth, 60.0);
[noteButton setImage:[UIImage imageNamed:#"note.png"] forState:UIControlStateNormal];
[noteButton addTarget:self action:#selector(tapOnNoteButton:) forControlEvents:UIControlEventTouchUpInside];
[noteButton setUrl:urls];
noteButton.backgroundColor = [UIColor clearColor];
[self.scrollViewNote addSubview:noteButton];
noteButtonXposition = noteButtonXposition + noteButtonWidth + 18;
return noteButtonXposition;
}
-(void)tapOnNoteButton:(ButtonClass*)sender
{
urlNote = sender.url;
[self performSegueWithIdentifier:#"goToNoteDetailsViewController" sender:urlNote];
}
-(void) ShowNoteDeleteButtonMethod:(NSMutableArray *) btnarray
{
countNoteButtonArray = [btnarray count];
// For delete button
deleteNoteButtonWidth = 14;
deleteNoteButtonXposition = 31;
for (NSString *idNumber in btnarray)
{
deleteNoteButtonXposition = [self addDeleteButton:deleteNoteButtonXposition AndURL:idNumber];
}
}
-(int) addDeleteButton:(int) xposition AndURL:(NSString *) idNumber
{
deleteNoteButton =[ButtonClass buttonWithType:UIButtonTypeCustom];
deleteNoteButton.frame = CGRectMake(deleteNoteButtonXposition, 74.0, deleteNoteButtonWidth, 20.0);
[deleteNoteButton setImage:[UIImage imageNamed:#"delete.png"] forState:UIControlStateNormal];
[deleteNoteButton addTarget:self action:#selector(tapOnDeleteButton:) forControlEvents:UIControlEventTouchUpInside];
[deleteNoteButton setIdNum:idNumber];
deleteNoteButton.backgroundColor = [UIColor clearColor];
[self.scrollViewNote addSubview:deleteNoteButton];
deleteNoteButtonXposition = deleteNoteButtonXposition + deleteNoteButtonWidth + 65;
return deleteNoteButtonXposition;
}
-(void)tapOnDeleteButton:(ButtonClass*)sender
{
idNumb = sender.idNum;
[self.sqLite deleteData:[NSString stringWithFormat:#"DELETE FROM note WHERE id IS '%#'", idNumb]];
// NSLog(#"idNumb %#", idNumb);
//[self.view setNeedsDisplay];
//[self.view setNeedsLayout];
//[self LoadNoteButtonAndDeleteButton];
//[self viewDidLoad];
// if ([self isViewLoaded])
// {
// //self.view = Nil;
// //[self viewDidLoad];
// [self LoadNoteButtonAndDeleteButton];
// }
}
//////////////*----------------------- Note Section (Up) -----------------------*//////////////
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"goToNoteDetailsViewController"])
{
NoteDetailsViewController *noteDetailsViewController = [segue destinationViewController];
[noteDetailsViewController setUrl:sender];
}
}
Here's the screen shot:
Here we can feel the difference between UIScrollView and UICollectionView, however UICollectionView is made up of UIScrollView, UICollectionView can be reload and adjust its content accordingly, where UIScrollView can't.
Ok, now in your case, you've to reload (refresh) your scroll view, which is not possible as we can with UICollectionView or UITableView.
You've two options,
Best option (little tough) : replace UIScrollView with UICollectionView - will take some of your time, but better for reducing code complexity and good performance of your app.
Poor option (easy) : Stay as it with UIScrollView - when you want to reload, delete each subview from it, and then again show and load everything. Highly not recommended.
IMHO, you should go with best option.
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;
}
}