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];
}
}
}
Related
I'm currently adding 5 textviews onto the viewcontroller programatically inside the viewDidLoad method.
for (int i = 0; i < 5; i++) {
//Add 5 textviews
UITextView *reqTV = [[UITextView alloc] initWithFrame:CGRectMake(30,30,250,50)];
reqTV.text = #"This is a textview";
[self.view addSubview:reqTV];
}
If later, I want to delete (not hide) these 5 textviews with a button click, how would I do that?
I have thought of using this, but am not sure how to call all 5 textviews to delete them.
- (void)removeTextViewButton:(id)sender {
[reqTV removeFromSuperview]; //remove textview
}
Thank you.
I see two easy ways:
You can save your textViews inside array as ivar of your controller.
And later remove each textView in array.
for (int i = 0; i < 5; i++) {
...
[textViews addObject: reqTV];
...
}
- (void)removeTextViewButton:(UIButton *)sender {
[textViews makeObjectsPerformSelector:#selector(removeFromSuperview)];
}
2. Assign static tag for each textView:
for (int i = 0; i < 5; i++) {
...
reqTV.tag = 1001; // for example
}
- (void)removeTextViewButton:(UIButton *)sender {
NSArray *subs = [NSArray arrayWithArray: self.view.subviews];
for (UIView *sub in subs) {
if (sub.tag == 1001) {
[sub removeFromSuperview];
}
}
}
Used code below to remove UITextViews:
- (void)removeTextViewButton:(id)sender {
NSArray *reqTVViews = [NSArray arrayWithArray: self.view.subviews];
for (UIView *tvView in reqTVViews) {
if ([tvView isKindOfClass:[UITextView class]]) {
[tvView removeFromSuperview];
}
}
}
When you are adding UITextFields on viewController use tag value to uniquely identify each textField.
You can store each tag value in an array for further use, eg.
#property (nonatomic, strong) NSMutableArray *tagArray;
NSMutableArray *tagArray = [NSMutableArray array];
for (int i = 101; i <= 105; i++ ) {
UITextField *txt = [UITextField alloc] init]; //for eg.
...
...
txt.tag = i;
[arr addObject:[NSNumber numberWithInt:i]];
[self.view addSubView:txt];
}
When you want to delete any of the textField or all then...
UIView *view = [self.view viewWithTag:<tag value>];
[view removeFromSuperview];
eg.
for (int i = 0; i < tagArray.count; i++) {
NSInteger tag = [[arr objectAtIndex:i] intValue];
UITextField *txt = (UITextField *)[self.view viewWithTag:tag];
[txt removeFromSuperview];
}
You can remove all subview in one go
- (void)removeTextViewButton:(id)sender
{
for (UIView *subview in views.subviews)
{
[subview removeFromSuperview];
}
}
Happy Coding.. :)
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;
}
I`m having problem with removing view from superview.
Adding view:
- (void)createCircles
{
NSString *currentDate = [self currentDate];
NSArray *array = [self.horizontalScroll subviews];
UILabel *label = nil;
for (label in array)
{
if ([label.text isEqualToString:currentDate])
{
UIView *view = [[UIView alloc] initWithFrame:label.frame];
view.backgroundColor = [UIColor redColor];
[self.horizontalScroll insertSubview:view atIndex:0];
[self.labelsArray insertObject:view atIndex:0];
}
}
}
Trying to remove:
- (void)labelTouch:(UITapGestureRecognizer*)sender
{
NSArray *array = [self.horizontalScroll subviews];
UILabel *label = (UILabel*)sender.view;
for (int i = 0; i < [array count]; ++i)
{
UILabel *l = array[i];
if (label.tag == l.tag)
{
UIView *view = nil;
view = [self.labelsArray objectAtIndex:0];
view.hidden = YES;
[view removeFromSuperview];
view = nil;
[self.labelsArray removeObjectAtIndex:0];
}
}
}
But after touch view is still displaying. Tried to remove label (l) - it is removed
Try this,
[[[self.horizontalScroll subviews] objectAtIndex:0] removeFromSuperView];
You should store reference to this "unkillable" view in ivar or property. Initialize it in first method and call removeFromSupperView in second.
I'm trying to create a scrollview with an array of clickable UIImageView's. My goal is that when an ImageView is clicked, it returns which position in the array it occupies. The problem is that i don't know how to "catch" the position's number. How do I do that?
So far I have:
- (IBAction)respondToTapGesture:(UITapGestureRecognizer *)recognizer {
NSLog(#"%#",)//here is where i want to return the element's position.
}
-(void) preenchemenu {
[menu setContentSize:CGSizeMake(400, 91)];
int x=0;
imagensmenu=[NSArray arrayWithObjects:[UIImage imageNamed:#"teste2.tiff"],[UIImage imageNamed:#"teste2.tiff"], nil];
for (int i = 0; i <3; i++) {
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(x,0 , 90, 91)];
x=x+90;
imageView.image = [imagensmenu objectAtIndex:i];
imageView.tag = 1000+ i;
imageView.userInteractionEnabled = YES;
imageView.multipleTouchEnabled = YES;
UITapGestureRecognizer *tapRecognizermenu = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(respondToTapGesture:)];
tapRecognizermenu.numberOfTapsRequired = 1;
[imageView addGestureRecognizer:tapRecognizermenu];
[menu addSubview:imageView];
}
}
You can create an array to hold you imageViews and then find the position of your imageView in this array when it is tapped.
Add a property for this
#property (nonatomic, strong) NSMutableArray *imageViews;
initialise it in init
- (id)init...
{
self = [super init...
if (self) {
_imageViews = [NSMutableArray array];
}
return self;
}
Then amend your current method slightly to also add the imageViews to this array as well as a subview of the menu
[self.imageViews addObject:imageView];
[menu addSubview:imageView];
Then in your gesture recognizer call back you can do
- (void)respondToTapGesture:(id)sender;
{
UIView *view = [sender view];
NSLog(#"%d", [self.imageViews indexOfObject:view]);
}
Just find the index by
- (IBAction)respondToTapGesture:(UITapGestureRecognizer *)recognizer
{
UIView *view = recognizer.view;
NSLog(#"Index of image in array is %d", view.tag-1000);
}
I have some dynamically allocated texfields and in which i am entering the text,
Now i have got two problems here
1) After 2-3 button clicks, i mean changing the views and coming back to the same view than the data is not being removed from the textfield the previous data in the textfield is being present.
the code i have tried with are
answerTextField.text = #"";
answerTextField.text = nil;
2) I am unable to delete the textfield data in which i am appending the data that is coming from the textfield.text
-(void) keyPressed: (NSNotification*) notification {
if ([[[notification object]text] isEqualToString:#" "])
{
UITextField *textField = (UITextField *)[self.view viewWithTag:nextTag];
textField.text = #"";
[textField becomeFirstResponder];
nextTag = textField.tag;
}
else
{
[[NSNotificationCenter defaultCenter] removeObserver: self name:UITextFieldTextDidChangeNotification object: nil];
NSLog(#"TextField tag value :%d",tagCount);
NSLog(#"TextField next tagg tag value :%d",nextTag);
if (tagCount == nextTag+1)
{
UITextField *textField = (UITextField *)[self.view viewWithTag:nextTag];
[textField resignFirstResponder];
NSLog(#"append string :%#",appendString);
}
else
{
NSLog(#"TextField nexttag value before :%d",nextTag);
nextTag = nextTag + 1;
NSLog(#"Letter is%#",[[notification object]text]);
str= [[NSString alloc]initWithFormat:#"%#",[[notification object]text]];
NSLog(#"TextField String :%#",str);
NSLog(#"TextField nexttag value after :%d",nextTag);
[appendString appendString:[NSString stringWithFormat:#"%#",str]];
NSLog(#"Content in MutableString: %#",appendString);
}
NSLog(#"The tags in keypressed:%d",nextTag);
UITextField *textField = (UITextField *)[self.view viewWithTag:nextTag];
[textField becomeFirstResponder];
}
// For inserting Spaces taken from array.
if(tagCount+300 == nextTag)
{
for (int m=0 ; m< [intArray count]; m++)
{
[appendString insertString:#" " atIndex:[[intArray objectAtIndex:m]intValue]];
NSLog(#"FinalString : %#",appendString);
}
}
}
Edited: The textfield data that i am storing is being made nil, but the on the textfield the data is being remained it is not being removed, for the textfield i have added a background image, do not know whether it makes any difference or not, i am attaching the code for it:
UIImageView *myView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"text_line.png"]];
myView.center = CGPointMake(5, 27);
[letterField insertSubview:myView atIndex:0];// mgViewTitleBackGround is image
[myView release];
To clear text field do this code in viewWillAppear:
NSArray *arraysubViews = [self.view subViews];
for(UIView *subView in arraysubViews){
if([subView isKindOfClass:[UITextField class]]){
// if(subView.tag == MY_TEXT_VIEW_TAG)
(UITextField *)subView.text = #"";
}
}
This will remove the text in every UITextField in your view. If you need to clear some textfields only, uncomment the code; which will check against tag value
EDIT
NSArray *arraysubViews = [self.view subviews];
for(UIView *subView in arraysubViews){
if([subView isKindOfClass:[UITextField class]]){
// if(subView.tag == MY_TEXT_VIEW_TAG)
UITextField *textField = (UITextField *)subView;
textField.text = #"";
}
}
UIView does not have a subViews method. It is subViews instead.