Access text values from dynamically created UITextFields. iOS - ios

I am creating UITextField 's in my view based on the count of an NSArray.
I want to know how I can access the text values based on the tag of the UITextField in my NSArray.
So after I add the below UITextField 's to my view how would I write code to retrieve .text values for myTextfield0, myTextfield1 and myTextfield2 respectively?
Example:
NSString *textFeildTextString = [NSString stringWithFormat:#"%#",myTextfield1.text];
Actual Code:
self.textFieldArray = [NSArray arrayWithObjects:#"one", #"two", #"three",nil];
NSMutableDictionary *myDict = [NSMutableDictionary dictionary];
for (int i=0; i<[self.textFieldArray count]; i++) {
UIView *spacerView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
UITextField *myTextField = [[UITextField alloc]initWithFrame:CGRectMake(20, 60*i+150, 280, 45)];
myTextField.borderStyle = UITextBorderStyleNone;
myTextField.font = [UIFont systemFontOfSize:14];
myTextField.returnKeyType = UIReturnKeyDefault;
myTextField.placeholder = NSLocalizedString(#"Answer", nil);
myTextField.inputAccessoryView = [super createInputToolbar];
myTextField.background = [UIImage imageNamed:#"TextFieldBg"];
myTextField.textColor = [UIColor appTextColorGrey];
[myTextField setLeftView: spacerView1];
myTextField.leftViewMode = UITextFieldViewModeAlways;
myTextField.delegate = self;
myTextField.tag = 200+i;
[myDict setObject:myTextField forKey:[NSString stringWithFormat:#"myTextfield%d", i]];
[self.view addSubview:myTextField];
}
NSLog(#"Dict: %#",myDict);
The NSlog of my UITexfields
2014-10-31 11:58:32.715 [51992:13536821] Dict: {
myTextfield0 = "<UITextField: 0x7faea14f8430; frame = (20 150; 280 45); text = ''; clipsToBounds = YES; opaque = NO; tag = 200; layer = <CALayer: 0x7faea14f82d0>>";
myTextfield1 = "<UITextField: 0x7faea14fae70; frame = (20 210; 280 45); text = ''; clipsToBounds = YES; opaque = NO; tag = 201; layer = <CALayer: 0x7faea14faca0>>";
myTextfield2 = "<UITextField: 0x7faea16dce30; frame = (20 270; 280 45); text = ''; clipsToBounds = YES; opaque = NO; tag = 202; layer = <CALayer: 0x7faea16d19c0>>";
}

for (int i=0; i<[self.textFieldArray count]; i++) {
UITextField *txt = (UITextField *)[myDict objectForKey:[NSString stringWithFormat:#"myTextfield%d", i]];
NSLog(#"Text %#",txt.text);
}

You can access them either by their tag :
UITextField *textField= (UITextField *)[self.view viewWithTag:200]; // Your first text field (201 your second etc..)
NSString *text = textField.text;
Or access them directly via your dictionary as you already know the key for each one of them:
UITextField *textField = (UITextField *)[myDict objectForKey:#"myTextField0"];
Note that in order for the dictionary to stay around declare a strong property member in your class and assign it to the created local dictionary (otherwise it will be lost by ARC) so at the end of the method you will have something like:
self.myDict = myDict;

Related

Custom UIView subClass with UIScrollView

I am creating a class, that creates an option bar with multiple scroll views accessible by buttons.
This is how I add the subview with its content:
NSArray *scroll1 = [NSArray arrayWithObjects:#"normal",#"tiltshift",#"zoom",#"normal",#"blur",#"outline",#"coming soon", nil];
NSArray *scroll2 = [NSArray arrayWithObjects:#"Emoji Natur-01",#"Emoji Natur-02",#"Emoji Natur-03",#"Emoji Natur-04",#"Emoji Natur-05",#"Emoji Natur-06",#"Emoji Natur-07",#"Emoji Natur-08",#"Emoji Natur-09",#"Emoji Natur-10",#"Emoji Natur-11",#"Emoji Natur-12", nil];
NSArray *scroll3 = [NSArray arrayWithObjects:#"Linear",#"Parallel",#"Parallel 2",#"Crescendo",#"Dubstep",#"Blackhole",#"coming soon", nil];
NSArray *content = [NSArray arrayWithObjects:scroll1,scroll2,scroll3, nil];
[self.view addSubview:[self.bottomOptionView initWithFrame:self.view.frame withContent:content]];
The Subclass then generate a scrollview for each Array, with the buttons based on the content of the array:
-(void)addScrollViewOfContent:(NSArray*)array{
int viewNumber = array.count;
for (int i = 0 ; i < viewNumber; i++) {
//create the main buttons
NSArray *content = array[i];
UIButton *buttonAccess = [UIButton buttonWithType:UIButtonTypeRoundedRect];
CGFloat buttonEdge = 40;
CGFloat buttonSpace = self.frame.size.width /viewNumber;
int placeOfButton = i+1;
CGFloat buttonAnchor = ((placeOfButton*(buttonSpace)) - (buttonSpace /2+ buttonEdge/2));
buttonAccess.frame = CGRectMake(buttonAnchor, 0 , buttonEdge, buttonEdge);
[buttonAccess setBackgroundColor:[UIColor redColor]];
buttonAccess.tag = i;
[buttonAccess addTarget:self action:#selector(buttonAccess:) forControlEvents:UIControlEventTouchDown];
[self addSubview:buttonAccess];
UIScrollView *ScrollView = [[UIScrollView alloc]init];
ScrollView.frame = CGRectMake(0, 50, self.frame.size.width, self.frame.size.height);
ScrollView.showsHorizontalScrollIndicator = YES;
ScrollView.tag = i;
ScrollView.backgroundColor =[UIColor colorWithRed:0 green:0.0 blue:0.0 alpha:0.0];
ScrollView.indicatorStyle = UIScrollViewDecelerationRateNormal ;
//UIImageView *selector = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"FILTER_SELECT.png"]];
CGFloat btnX = 0;
for (int i = 0 ; i < content.count; i++)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(btnX, 2 , 65, 65);
UIImage *img = [UIImage imageNamed:[content objectAtIndex:i]];
[button setBackgroundImage:img forState:UIControlStateNormal];
[button addTarget:self action:#selector(subButtonTarget:) forControlEvents:UIControlEventTouchDown];
button.tag = i;
[button setTitle:[content objectAtIndex:i] forState:UIControlStateNormal];
button.titleLabel.font = [UIFont fontWithName:#"MyriadPro-Cond" size:15];
button.titleLabel.textColor = [UIColor whiteColor];
button.titleLabel.textAlignment = UIBaselineAdjustmentAlignBaselines ;
button.showsTouchWhenHighlighted = YES;
[ScrollView addSubview:button];
btnX = btnX + 100;
}
btnX = btnX - 80;
ScrollView.contentSize = CGSizeMake(btnX + 50, 80);
ScrollView.hidden = YES;
[self.scrollViewArray addObject:ScrollView];
[self addSubview:ScrollView];
}
This gives me exactly what I want.
Then I detect which button, of which scroll view is pressed to trigger the action.
-(void)subButtonTarget:(UIButton *)sender{
int button = sender.tag;
int scrollview = self.selectedScrollView;
[self.videoEditor subAction:button ofScrollView:scrollview];
}
-(void)buttonAccess:(UIButton *)sender{
// self.selectedScrollView = sender.tag;
for (int i=0; i< self.scrollViewArray.count; i++) {
UIScrollView *scrollview= [self.scrollViewArray objectAtIndex:i];
scrollview.hidden= YES;
}
int scrollIndex = sender.tag;
UIScrollView *scrollview= [self.scrollViewArray objectAtIndex:scrollIndex];
scrollview.hidden = NO;
}
Basically when one of the button is touched, it calls a function in the view controller in which the sublclass was initially called.
The problem is that, on touchevent nothing happens, except for NSLog. Would that be because of the dependency relation of the subClass and the VC that uses it?
You should set this one for each UIScrollView
ScrollView.delaysContentTouches = NO;
And try to subclass UIScrollView with override method
-(BOOL)touchesShouldCancelInContentView:(UIView *)view
{
return YES;
}

How to create dynamic uitextfiled inside a loop and make all them editable mode?

I am continuously facing problem to create uitextfield programmatically inside a loop and make all them in editable mode?
I have created successfully text fields inside the loop but problem is that. the last one i.e. the last text field is in editable mode.
EX:
suppose an array (myarray) has 5 values.
-(void)createDynamic_textfld{
UITextField *roomratetxt;
UIScrollView *scrlsummery;
NSMutableArray *myarray = [NSMutableArray arrayWithObjects:#[#"one",#"two",#"three",#"four",#"five"], nil];
for (int i = 0; [myarray count]; i ++){
roomratetxt = [[UITextField alloc]init];
roomratetxt.frame = CGRectMake(200, 0, 90, 20);
roomratetxt.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"lighttextcolor.png"]];
roomratetxt.backgroundColor = [UIColor clearColor];
roomratetxt.font = [UIFont systemFontOfSize:12];
roomratetxt.text = [NSString stringWithFormat:#"%#",[myarray objectAtIndex:i]];
roomratetxt.textAlignment = NSTextAlignmentRight;
[roomratetxt setTag:i];
[roomratetxt setDelegate:(id)self];
[scrlsummery addSubview:roomratetxt];
}
}
i want to make all 5 textfields in editable mode. but as of now, the last textfield is only in editing mode and the rest all are non editable mode.
Can anyone plz suggest me some ideas ?How to achieve this
Thanks in advance.
Ajeet Kumar
First of all you need to provide different frames for that you can them in different position. Your above code looks correct and it must be in editable mode. I execute below snippet on my project and it works like a charm. I am assuming you are using Scrollview and added all textfield in it. Only thing make sure you are not disabling them from
(BOOL)textFieldShouldBeginEditing:(UITextField *)textField; // return NO to disallow editing.
or
(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string; // return NO to not change
text
for (int i = 0; [myarray count]; i ++){
roomratetxt = [[UITextField alloc]init];
roomratetxt.frame = CGRectMake(200, i*20, 90, 20);
roomratetxt.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"lighttextcolor.png"]];
roomratetxt.backgroundColor = [UIColor clearColor];
roomratetxt.font = [UIFont systemFontOfSize:12];
roomratetxt.text = [NSString stringWithFormat:#"%#",[myarray objectAtIndex:i]];
roomratetxt.textAlignment = NSTextAlignmentRight;
[roomratetxt setTag:i];
[roomratetxt setDelegate:(id)self];
[scrlsummery addSubview:roomratetxt];
}
-(void)createDynamic_textfld{
UITextField *roomratetxt;
UIScrollView *scrlsummery;
NSMutableArray *myarray = [NSMutableArray arrayWithObjects:#[#"one",#"two",#"three",#"four",#"five"], nil];
for (int i = 0; [myarray count]; i ++){
roomratetxt = [[UITextField alloc]init];
roomratetxt.frame = CGRectMake(200, i*0, 90, 20);
roomratetxt.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"lighttextcolor.png"]];
roomratetxt.backgroundColor = [UIColor clearColor];
roomratetxt.font = [UIFont systemFontOfSize:12];
roomratetxt.text = [NSString stringWithFormat:#"%#",[myarray objectAtIndex:i]];
roomratetxt.textAlignment = NSTextAlignmentRight;
[roomratetxt setTag:i];
[roomratetxt setDelegate:(id)self];
[scrlsummery addSubview:roomratetxt];
}
}
The frame of all 5 textField are putting in the same position. You might need to change their frame as well.
for (int i = 0; [myarray count]; i ++){
roomratetxt = [[UITextField alloc] init];
roomratetxt.frame = CGRectMake(200, i*60, 90, 20);
roomratetxt.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"lighttextcolor.png"]];
roomratetxt.backgroundColor = [UIColor clearColor];
roomratetxt.font = [UIFont systemFontOfSize:12];
roomratetxt.text = [NSString stringWithFormat:#"%#",[myarray objectAtIndex:i]];
roomratetxt.textAlignment = NSTextAlignmentRight;
[roomratetxt setTag:i];
[roomratetxt setDelegate:(id)self];
[scrlsummery addSubview:roomratetxt];
}

iOS Image View turn off selection highlighting

Bit of a strange question, so i've attached a screen recording to help...
Video : https://www.dropbox.com/s/3aaefixsk8eejln/Error.mov (See past the watermark!)
My issue is that in my application when the user is at the "Preview" view and is reviewing their images, each time the image is selected, the image receives a touched overlay, which could be confusing for a user as nothing happens when touched.
I would like to disable this if possible..
Below is the example code to how the images are being displayed..
- (void)setReviewImages
{
continueButtonDisabled = YES;
downloadedImageCount = 0;
NSArray *reviewViews = scrollView.subviews;
for (IMReviewView *reviewView in reviewViews) {
[reviewView removeFromSuperview];
}
NSUInteger photoCount = [[IMLocalUser localUser] cachedPhotoCount];
if ( nPageNum == 0 ){
for (NSUInteger i = 0; i < photoCount; i++) {
CGRect frame;
frame.origin.x = scrollView.frame.size.width * i;
frame.origin.y = 65;
frame.size = CGSizeMake(scrollView.frame.size.width, 327.0f);
IMReviewView *subview = [[IMReviewView alloc] initWithFrame:frame];
subview.delegate = self;
subview.photo = [[IMLocalUser localUser] cachedPhotoAtIndex:i];
[scrollView addSubview:subview];
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * i, scrollView.frame.size.height);
UILabel *headingLabel = [[UILabel alloc] initWithFrame:CGRectMake(12, 20, 300, 30)];
[self.view addSubview:headingLabel];
headingLabel.text = #"Time To Preview!";
headingLabel.textColor = [UIColor blackColor];
headingLabel.textAlignment = UITextAlignmentCenter;
headingLabel.textAlignment = NSTextAlignmentCenter;
headingLabel.tag = 10;
headingLabel.backgroundColor = [UIColor clearColor];
headingLabel.font = [UIFont boldSystemFontOfSize:26.0f];
headingLabel.hidden = NO;
headingLabel.highlighted = YES;
headingLabel.highlightedTextColor = [UIColor blackColor];
headingLabel.lineBreakMode = YES;
headingLabel.numberOfLines = 0;
}
It seems to me like IMReviewView has a UIButton subview. If so, try to set its adjustsImageWhenHighlighted property to NO.

how to access dynamically created uilabel in iphone

I have created dynamic UILabel with tag value and i have similar kind of other labels without tag values.
Now i want access only tag values labels but i was not able to acces the label text value.
Here is my code.
Dynamic created Label
for (int i= 0; i < [array count]; i++) {
UILabel *defaultLbl = [[UILabel alloc] initWithFrame:CGRectMake(30, 70, 60, 21)];
defaultLbl.text = #"Default";
defaultLbl.backgroundColor = [UIColor clearColor];
defaultLbl.textColor = [UIColor colorWithRed:51.0/255.0 green:51.0/255.0 blue:51.0/255.0 alpha:1.0];
[defaultLbl setFont:[UIFont fontWithName:#"Helvetica" size:12]];
defaultLbl.textAlignment = NSTextAlignmentCenter;
defaultLbl.tag = i+1;
[myButton addSubview:defaultLbl];
[defaultLbl release];
UILabel *masterProName = [[UILabel alloc] initWithFrame:CGRectMake(28, 20, 200, 21)];
masterProName.text = [masterProjListArray objectAtIndex:i];//#"Lorem Ipusum";
masterProName.backgroundColor = [UIColor clearColor];
masterProName.textColor = [UIColor colorWithRed:51.0/255.0 green:153.0/255.0 blue:204.0/255.0 alpha:1.0];
[masterProName setFont:[UIFont fontWithName:#"Helvetica-Bold" size:17]];
masterProName.lineBreakMode = NSLineBreakByCharWrapping;
[myButton addSubview:masterProName];
[masterProName release];
UILabel *masterProID = [[UILabel alloc] initWithFrame:CGRectMake(28, 45, 200, 21)];
masterProID.text = [masterProjIDArray objectAtIndex:i];//#"133 FS";
masterProID.backgroundColor = [UIColor clearColor];
masterProID.textColor = [UIColor colorWithRed:51.0/255.0 green:51.0/255.0 blue:51.0/255.0 alpha:1.0];;
[masterProID setFont:[UIFont fontWithName:#"Helvetica" size:17]];
masterProID.lineBreakMode = NSLineBreakByCharWrapping;
[myButton addSubview:masterProID];
[masterProID release];
}
And UILabel access method after user press the long press button
- (void)longPressTap:(UILongPressGestureRecognizer *)sender
{
if ([recognizer.view tag]) {
UILabel *view = (UILabel *)recognizer.view;
NSLog(#"---%#", view.subviews);
for (UILabel *lbl in view.subviews) {
if (recognizer.view.tag == view.tag) {
NSString *text = view.text;
NSLog(#"---%#", text);
}
}
}
}
here am putting the log
"<UIImageView: 0x75b9510; frame = (0 0; 379 100); clipsToBounds = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x75acef0>>",
"<UILabel: 0x88c4e50; frame = (28 20; 200 21); text = 'Aux Water Waste Trtmnt'; clipsToBounds = YES; userInteractionEnabled = NO; layer = <CALayer: 0x88c49c0>>",
"<UILabel: 0x88c52f0; frame = (28 45; 200 21); text = 'M10000'; clipsToBounds = YES; userInteractionEnabled = NO; layer = <CALayer: 0x88c5380>>",
"<UILabel: 0x88c56c0; frame = (30 70; 60 21); text = '**Default**'; clipsToBounds = YES; userInteractionEnabled = NO; tag = 1; layer = <CALayer: 0x88c5750>>",
"<UIButton: 0x88c6440; frame = (240 10; 70 80); opaque = NO; userInteractionEnabled = NO; tag = 1; layer = <CALayer: 0x88c6500>>"
In this log i want to access only "Default" text label
Please give me any suggestion on this.
Well, you need to know which value the tag has of the lable with "Default" in its text. Let's assume it is 42. Then
UILabel *label = [view viewWithTag:42];
would do the trick.
Anyway your solution should work too. Have a look at the actual tag values that you are dealing with. i've got a guts feeling that recognizer.view.tag does not have the same value as the tag of the label with "Default" in it.
You can also create outlets of those at runtime.
Create an array, and go on to add outlets of each label.
Once you are done and need to retrieve them you can easily access by index of arrays.
Even you can create a dictionary for storing outlets, here you can access labels by keys.
As you are assigning tag to UILabel, we can get label from tag (if it known to us, in your case we know).
So give it a try this way
for (int i = 0 ; i <[array count]; i++)
{
UILabel *lbl = (UILabel*)[self.view viewWithTag:i+1];
NSLog(#"--- %#", lbl.text);
}
for get UILabel base on its Tag.
Take int i; in .h file,
And put i=1; in above for Loop
for (NSObject *view in self.View.subviews)
{
if ([view isKindOfClass:[UILabel class]])
{
label = (UILabel *)[[self view] viewWithTag:i];
NSLof(#"%#".label.text);
// break;
}
i++;
}
Firstly, you should be checking
if (lbl.tag == view.tag)
not
if (recognizer.view.tag == view.tag)
Secondly, it won't work anyway. All that does is identify the view that has been touched which you know. How about setting the tag value in the label you want to a unique number and testing
if (lbl.tag == <unique tag number>)

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