How to select programmatically created text fields? - ios

I am adding text fields to a view programmatically like this:
// Add a text field.
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 100, 280, 40)];
textField.returnKeyType = UIReturnKeyNext;
[textField becomeFirstResponder];
[textField addTarget:self action:#selector(nextButtonPressed:) forControlEvents:UIControlEventEditingDidEndOnExit];
UITextField *textFieldTwo = [[UITextField alloc] initWithFrame:CGRectMake(20, 160, 280, 40)];
textFieldTwo.returnKeyType = UIReturnKeyDone;
[textFieldTwo addTarget:self action:#selector(doneButtonPressed:) forControlEvents:UIControlEventEditingDidEndOnExit];
How can I select these fields later on?
I know how to do this when I'm creating things using UI, but how does this work for dynamically added elements?
Example: I want to focus the second field when "Next" button is pressed.
Thanks!

There are at least two ways of doing it:
Give each of your dynamically created fields a distinct tag, and then retrieve the required field using the tag that you gave it by calling viewWithTag: on the view to which you added your fields, or
Make textField and textFieldTwo instance variables of your class, initialize them when you have to, and then refer to these ivars later when you want to send input to them.
The second way is close to what you do when you add the fields through the Interface Builder. The only difference is that in this case the fields are added programmatically.

In this case, I usually set a tag for each textfield present on my viewController, and assign them my viewController as delegate :
// You should use const to identify quickly your tag
textField.tag = 10;
textFieldTwo.tag = 11;
textField.delegate = self;
textFieldTwo.delegate = self;
Then I implements the textFieldShouldReturndelegate method :
#pragma mark - UITextFieldDelegate protocol conformance
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
NSInteger nextTag = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// Not found, so remove keyboard.
[textField resignFirstResponder];
}
return NO; // We do not want UITextField to insert line-breaks.
}
By doing so, you can have multiple UITextField with a focus moved from one to another without having to implements multiple UIControlEventEditingDidEndOnExit event methods.

You can get these by there tag value. For this
1.. set a unique tag value, to each textField at time of creation. (like 45 for first, and 78 for second textfield)
textField.tag = 45;
2.. suppose your you have added these textField as subView on 'myView'.
UITextField *txtField = (UITextField*)[myView viewWithTag:45];
this line will give you textfield having tag 45, which is added on myView.
Note -- Avoid to use '0' as tagValue for any control because '0' is used as byDefault tagValue for controls.

On UIControlEventEditingDidEndOnExit event for the first textField, call [textFieldTwo becomeFirstResponder].

Related

I am getting error like "Assignment to read only property" in UIView

If VIN is an text field this code works for me to Hiding keyboard without breaking UITextField functionality..
UIView *dummyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
VIN.inputView = dummyView;
But in another case i need to do same thing for UIVIEW.. it is possible to do for UIView ?
UIView *dummyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
VIN.inputView = dummyView;
In this case VIN Is an UIView.. i am getting error like "Assignment to read only property".
UITextfield has inputview. Default inputview is keyboard. uiview has not input view that you can set so you can't assign input view to UIView.
And for hiding keyboard you should call resignFirstresponder like,
[myTextField resignFirstResponder];
This will hide keyboard and when you click textfield it will show keyboard again so you should do like this.
Hope this will help :)
If you want to hide or disable keyboard for particular textfield , you can use following textfield delegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
// Here You can do additional code or task instead of writing with keyboard
if (textField == YourTextField)
{
return NO;//Keyboar Wont appear for textfield
}
return YES;
}

How to hide the subView based on textfield value in iOS?

I am having four SubViews and two TextFields stateText and providertext.
If I click the stateText it shows a UIPickerView with two values. If I select the first value in the UIPickerView the view should not change and if I select the second value, this means that only third SubView has to change. In the same time, the selected picker value populates to TextFields.
If I select second value means the third SubView changes. But TextField values are not populated. Only this newSubView becomes active. Here is my Code:
PickerView Done Action
if([stateText.text isEqual:#"SecondValue"])
{
[self newSubView];
}
-(void)newSubView
{
UIView *loginView = [[UIView alloc]initWithFrame:CGRectMake(0, self.navigationController.navigationBar.frame.size.height+160, self.view.frame.size.width, 150)];
loginView.backgroundColor = [UIColor yellowColor];
[self.view addSubview:loginView];
}

How to programmatically deselect UITextField

I have a UITextField which I can click on, and edit the contents of. I am running code when the UITextField is pressed by using:
[personalCountryLabel addTarget:self action:#selector(countryPressed) forControlEvents:UIControlEventEditingDidBegin];
This presents another view controller. However, when I click the back button, the UITextField is still selected, so the text runs again, sending me back to the view controller.
I use the code:
textField.enabled = false;
and
textField.enabled = true;
to respectively turn off and on the editing of the UITextField, but doing this in succession does not unselect the UITextField.
How can I therefore programmatically deselect the UITextField (i.e, where the line cursor is no longer blinking).
If I understand what you're asking correctly, you just want:
[textField resignFirstResponder];
/* Programmatically deselect the Uitextfiels below this Code */
UITextField *txtDeselect = [[UITextField alloc]initWithFrame:CGRectMake(self.view.frame.origin.x+20, self.view.frame.origin.y+20, self.view.frame.size.width-40, 40)];
[txtDeselect setBackgroundColor:[UIColor yellowColor]];
[txtDeselect setBorderStyle:UITextBorderStyleRoundedRect];
[txtDeselect setTextAlignment:NSTextAlignmentCenter];
[txtDeselect setText:#"Email"];
txtDeselect.enabled = NO;
[self.view addSubview:txtDeselect];
did you set outlet & delegate of UITextField in your view controller ?
why you use UItextfield for this ?
i recommend you use one of this before presenting new view controller :
option 1 :
[youtextfield resignFirstResponder];
//please sure you outlet connected & ....
you can call this on your viewWillAppear
option 2 :
[self.view endEditing:YES]; // this regularly
happend after present another VC)
you shouldn't use shouldEndEditing

Adding default text to UITextView

I was wondering how to display a default prompt in a UITextView. If I wanted the user to type a description in a text view, the UITextView could have "description" printed in it, and when the user starts to type, it disappears.
For UITextField, there is the placeholderText property, which will display a grayed out text that is removed once the user starts typing.
For UITextView, you can use a custom implementation, such as SZTextView, which implements a similar functionality of a placeholder text.
It wont be a wise idea to use a third party uitextview for placeholder property.
Follow these steps and you will achieve what you need-
set- textview.textcolor=[uicolor greycolor];
textview.text=#"Your initial placeholder text";
Now in -textViewShouldBeginEditing write these lines of codes-
if(textview.color==[uicolor greycolor]){
textview.color=[uicolor blackcolor];
textview.text=#"";
}
Cheers.
The below solution from #svmrajesh isn't complete. You still need to implement an auto-delete functionality so the default text deletes as soon as the user selects the textView.
In my implementation I set the text in the UITextView to lightGrayColor initially so that it looks like default text
[textView setTextColor:[UIColor lightGrayColor]];
Then in the header file I implement the UITextViewDelegate.
#interface YourViewController <UITextViewDelegate>
Then I set the UITextView delegate to self.
[textView setDelegate:self];
Then simply I implement the following delegate method which is fired when the user selects the textView to start typing in their text. The first thing it does is to check if the text color is still set to lightGray.
If it is then the default text is still being displayed, so it is deleted and the textColor is set to black. This simple solution works well for me.
-(void)textViewDidBeginEditing:(UITextView *)textView
{
if(textView.textColor == [UIColor lightGrayColor])
{
textView.textColor = [UIColor blackColor];
textView.text = #"";
}
}
Try this....
For UITextView :
UITextView *myUITextView = [[UITextView alloc] init];
myUITextView.delegate = self;
myUITextView.text = #"placeholder text here...";
For UITextField :
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 150, 200)];
textField.placeholderText = #"Enter your text here";
[self.view addSubview textField];

Using a UIButton inside a UITextField as a clear button

what i am trying to do is do a custom clear button in a UITextField, currently i have got everything working except for the last part. Which is getting it to preform the clear action. However, i have not been able to work out how i can get it to clear, just the textField it is in.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
[textField setTextColor:[UIColor colorWithRed:0.56f green:0.56f blue:0.56f alpha:1.00f]];
[textField setFont:[UIFont systemFontOfSize:14]];
textField.background = [UIImage imageNamed:#"whiteCell"];
UIButton *btnColor = [UIButton buttonWithType:UIButtonTypeCustom];
[btnColor addTarget:self action:#selector(clearText:) forControlEvents:UIControlEventTouchUpInside];
btnColor.frame = CGRectMake(0, 0, 25, 25);
[btnColor setBackgroundImage:[UIImage imageNamed:#"clearBut"] forState:UIControlStateNormal];
textField.rightView = btnColor;
textField.rightViewMode = UITextFieldViewModeAlways;
[textField addSubview:btnColor];
return YES;
}
This is how i've created the button in the textField, and for it to only show when editing, as you can see i have it calling clearText however i'm unsure how i can send the current textField name i am in to be cleared in the clearText call.
I know I can do it the hard way, and define it individually for each of my textFields, but i'm sure there is an easier way to go about this, that i just haven't realized.
I suggest subclassing UITextField. This will not allow you to lay out the button in a Storyboard, but in Code or as a .nib file should work. Of course you can use the UITextfield subclass in a storyboard.
Inside the subclass add a UIButton as a subview and in its action method call:
self.text = #""
Let me know if you have any further questions.
Given that your button has been added to the text field as a sub-view you can get to the text field in the buttons superview property:
- (void) clearText:(UIButton*)sender
{
UITextField* textField = (UITextField*)sender.superview;
textField.text = nil;
}

Resources