How to find the selected text field in iOS - ios

I am developing one iPad application using story board.In my application i have popup view with two text fields and one button.what i need to do means if i click the button one text is need to display in the selected text box. How i find which text box is selected at the present situation? Example code is give below Please help me to complete function.
- (IBAction)buttonPressed:(id)sender {
if(//Here i need to set the condition for check selected text box is first){
texbox1.text=#"User";
}
else{
textbox2.text =#"Admin";
}
}

- (IBAction)buttonPressed:(id)sender {
if([textbox1 isFirstResponder]){
//Cursor on textbox1
texbox1.text=#"User";
}
else if([textbox2 isFirstResponder]){
//Cursor on textbox2
textbox2.text =#"Admin";
}
else{
NSLog(#"None of them have cursor");
}
}

Set Tag to your textfields
Implement UITextFieldDelegate in your class
Use this methods
- (void)textFieldDidBeginEditing:(UITextField *)textField {
if (textField.tag == your tag) {
selectedTextField = textField; //selectedTextField is an UITextfield variable
}
}
Use it in your IBAction
- (IBAction)buttonPressed:(UIButton *)sender {
selectedTextField.text = #"abc";
}
//Edit: something wrong with StackOverFlow's code function, doesn't display properly

If I understand your question correctly, I think the below code is what you want:-
- (IBAction)buttonPressed:(UIButton *)sender {
if(self.texbox1.isFirstResponder){
self.texbox1.text=#"User";
[self.texbox1 resignFirstResponder];
}
if(self.texbox2.isFirstResponder){
self.texbox2.text=#"Admin";
[self.texbox2 resignFirstResponder];
}
}
I am not sure why you want to implement as above though as it is a bit funny.

UITextField is a subclass of UIResponder which allows you to perform checks including isFirstResponder which may be what you are looking for. However you will need to understand how the responder chain works and if this is really the behavior you are trying to detect.

Use isFirstResponder to check which textbox is active.
- (IBAction)buttonPressed:(id)sender {
if([textbox1 isFirstResponder]){
texbox1.text=#"User";
}
else if([textbox2 isFirstResponder]) {
textbox2.text =#"Admin";
} else {
// What should happen when neither textbox1 nor textbox2 is active?
}
}

Related

Changing the return key type while still editing UITextField?

IM having an issue with changing the return keys type while still editing the textfield of my view. So when the user clicks the textfield i have a few checks that change the return type of the keyboard, these checks are placed in - (void)textFieldDidBeginEditing:(UITextField *)textField, when i change the keyboards return key here the code works fine. Im just changing the keyboards retrun key like so [textField setReturnKeyType:UIReturnKeyDone];. So there are 2 textfields username and password. If theres text in both the textfields i want to change the return key to DONE if theres text in only one of the text fields i want to change it to NEXT so i can jump back and forth between the textfields.So now im placing some checks and balances in - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string. Yet the same code im placing in textFieldDidBeginEditing is not working in this function. Ive read a bunch of posts and they all say to remove the text field as the first responder then set the return key and become the responder again, but this messes up my current flow in the respective methods. I also read that i have to call [textfield reloadInputFields] after setting the return key, yet again this does not work. You would think that apple would have fixed a bug like this by now. Anyway does anyone have some input here?
I had to implement an add tag logic that required to change the keyboard return key depending on the text typed into the UITextField. Finding how to change the return key was quite easy, but when I started testing, I noticed that this solution only works for iOS10, but not for iOS9. After spending some time and doing some research, I came up with this workaround, it's not the nicest but at least it works.
if #available(iOS 10.0, *) {
textField.reloadInputViews()
} else {
textField.keyboardType = .numberPad
textField.reloadInputViews()
textField.keyboardType = .default
textField.reloadInputViews()
}
Try it out and Let me know
I have made demo for your question and its running perfect as per your need or you can modify it as per
// This is the Editing Changed Action Event of Both textField Created From StoryBoard
- (IBAction)txtEditingChanged:(UITextField *)sender
{
[sender resignFirstResponder];
[sender becomeFirstResponder];
}
// This is the Editing Did End Action Event of Both textField Created From StoryBoard
- (IBAction)txtEditingEnd:(UITextField *)sender
{
if (txtUserName.text.length == 0 || txtPassword.text.length == 0)
{
[txtUserName setReturnKeyType:UIReturnKeyNext];
[txtPassword setReturnKeyType:UIReturnKeyNext];
}
else
{
[txtUserName setReturnKeyType:UIReturnKeyDone];
[txtPassword setReturnKeyType:UIReturnKeyDone];
}
}
// This is Next And Done Button Events i.e. UITextField Delegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == txtUserName && textField.returnKeyType == UIReturnKeyNext && textField.text.length != 0)
{
[txtPassword becomeFirstResponder];
}
else if (textField == txtPassword && textField.returnKeyType == UIReturnKeyNext && textField.text.length != 0)
{
[txtUserName becomeFirstResponder];
}
else
{
// This is your Done Button Event You Can Procced Here
}
return YES;
}

iOS text validation in story board for 10+ textfields

I have a form with more than 10 text fields. I want to check if all are entered. I know the following way to check the same
if ([_fName.text isEqualToString:#""])
Is it the best way even if we have more than 10 text fields? or is there any simpler way?like assign something in storyboard or something?
You can conform your view controller to <UITextFieldDelegate> protocol and implement:
- (void)textFieldDidEndEditing:(UITextField *)textField {
if ([textField.text isEqualToString:#""]) {
// your code
}
}
In addition your can check which exactly textField was changed and apply custom validation logic:
- (void)textFieldDidEndEditing:(UITextField *)textField {
if (textField == self._fName) {
// your code
}
}
You can use textFieldDidEndEditing for tracking text:
- (void)textFieldDidEndEditing:(UITextField *)textField {
switch (textField.tag) {
case NameFieldTag:
// do something with this text field
break;
case EmailFieldTag:
// do something with this text field
break;
}
}
I suggest you do something like below. Note, you will probably want to do more than validate if something exists in the fields. You might want to check validity of dates, numbers, etc as well.
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
// assuming you have a save bar button or equivalent
// disable it or change it from 'Edit' to 'Save' when you start changing textFields
self.navigationItem.rightBarButtonItem.enabled = NO;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
// validate form
if (_textField1.text.length > 0 &&
_textField2.text.length > 0 &&
_textField3.text.length > 0 &&
_textField4.text.length > 0 &&
_textField5.text.length > 0)
{
// Re-enable your bar button or change it from 'Edit' to 'Save'
// if form validates
self.navigationItem.rightBarButtonItem.enabled = YES;
}
}

How do you disable keyboard for specific UITextField in same ViewController?

I have four text fields in a ViewController, and want to disable the keyboard for two of them (textField1 and textField2).
I have tried implementing the following after assigning the text fields as delegates in viewDidLoad
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField) {
if ([self.textField1 isTouchInside] || [self.textField2 isTouchInside] {
return NO;
} else {
return YES;
}
}
However, this disables the keyboard for the ViewController completely, so it will not appear when trying to edit textField3 and textField4. How can I get around this problem?
For example, is there a way to refresh the run textFieldShouldBeginEditing method again after editing ends on a textField?
Also, I know I can create a label to accomplish something similar, but I would prefer to use a text field in my case.
EDIT: So I left out a big detail. I am firing an IBaction when pressing textField1 and 2. However, Lootsch's answer gave me an idea.
In the textField1/2Pressed IB action, I ran the textfield.enable:NO methods, then I re-enabled them when I fired a second action which submitted data to the textfields, such as below
- (IBAction)textField1Pressed:(id)sender {
self.textField.Enabled = NO;
}
- (IBAction)submitToTextField1:(id)sender {
self.textField.text = #"blah blah";
self.textField.Enabled = YES;
}
Albeit, this requires having two entering an exiting actions, but it worked for me. Also, I did not have to manipulate the textFieldShouldBeginEditing method with this solution.
You should disable these two textFields (in code or via IB) or you can disable the user interactions (different appearance, same function):
textField3.enabled = NO;
textField4.enabled = NO;
Or:
textField3.userInteractionEnabled = NO;
textField3.userInteractionEnabled = NO;
The second approach won't change the appearance of the UITextFields, while the first will indicate, that these TextFields are disabled.
something like should do
if (textField==textField1 || textField==textField2) [textField resignFirstResponder];
Please try this
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if (textField==self.textField1 || textField==self.textField2)
{
return NO;
}
else
{
return YES;
}
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)mytextField
{
if((mytextField.tag == 104) || (mytextField.tag == 105) || (mytextField.tag == 106))
{
if(mytextField.tag == 104)
{
point = 50;
// if(textField1.tag == 4)
{
[self showDatePickerWithTitle:#"Select DOB"];
return NO;
}
//
}
}
else
{
retutn YES;
}
//you can also try this piece of code.With tag property of textfield.And make sure your tag is not zero,because the default tag is 0 for the main view.

ios textFieldDidEndEditing fires, but textFieldShouldReturn doesn't

In my app i'm using a UITextField collect a string value. Whenever i finish editing the field, textFieldDidEndEditing gets fired, but later textFieldShouldReturn never. What can be it's reason?
I provide some code:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
if(textField == self.urlPatternTextField) {
/*do some stuff*/
}
}
- (IBAction)dismissKeyboard:(id)sender {
NSMutableArray* possibleReponders = [[NSMutableArray alloc]initWithObjects:
self.urlPatternTextField, nil];
for (UITextView* tv in possibleReponders) {
if([tv isFirstResponder]) {
[tv resignFirstResponder];
return;
}
}
}
Note:
In textFieldDidEndEditing the if condition is true.
Thanks for the help in advance.
Sincerely,
Zoli
textFieldShouldReturn:
Asks the delegate if the text field should
process the pressing of the return button.
- (BOOL)textFieldShouldReturn:(UITextField *)textField
Parameters
textField The text field whose return button was pressed.
Return Value
YES if the text field should implement its default behavior for the
return button; otherwise, NO.
Discussion The text field calls this method whenever the user taps the
return button. You can use this method to implement any custom
behavior when the button is tapped.
The method invokes when return button is pressed.Try it so

How to disable keyboard appearing when hitting on a text field , iOS?

I have a text field , and i need when the user presses it to show a custom picker.
The picker is shown fine , but the problem is that the keyboard appears on the bottom and i dont want that.
This is an iPad project which i am trying to convert from my iphone one. On the iPhone , this works well and the keyboard is always hidden.
What could i be missing/forgetting to do here ?
EDIT
For future reference what actually happened here , was that in fact both times (iphone & ipad) the keyboard was not hidden. I just thought that it was hidden in the iphone because my picker , which was popping from the bottom was hiding the keyboard as it was on top of it. But on ipad this wasnt the case.
Anyway i fixed it , using the delegate method suggested below.
Caution , i accepted this answer cause it was the one answering specifically what i wanted. The rest of the answers are correct and my considered better for other implementations.
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
// Here You can do additional code or task instead of writing with keyboard
return NO;
}
this delegate method will get called first when you hit to textfield and if you write NO as a boolean value means you dont want to begin editing so it will not present Keyboard.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if(textfield == yourtextField)
{
[textfield resignFirstResponder];
// Show you custom picker here....
return NO;
}
}
and you need to implement the uitextfielddelegate in the controller.
and give assign the delegate to yourtextField.
Use textfield delegate.
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
return NO;
}
It looks like all of these answers take one approach, to simply deny the keyboard before it comes up. This prevents first responder status, which has many advantages.
One simple approach that allows you to maintain first responder status is to create an empty view and assign that to the inputView property on your input field. If you are using iOS 9 (or later?) you will also have to get rid of the inputAssistantItem objects as well.
UITextField *field = [[UITextField alloc] init];
field.inputView = self.emptyKeyboard.view;
UITextInputAssistantItem *aItem = [field inputAssistantItem];
aItem.leadingBarButtonGroups = #[];
aItem.trailingBarButtonGroups = #[];
Then if you want to control the field from an alternate view controller, you can do so by adding targets:
[field addTarget:self.numberPad action:#selector(editingBegan:) forControlEvents:UIControlEventEditingDidBegin];
[field addTarget:self.numberPad action:#selector(editingEnded:) forControlEvents:UIControlEventEditingDidEnd];
[field addTarget:self.numberPad action:#selector(fieldChanged:) forControlEvents:UIControlEventEditingChanged];
It is also possible to do this a lot more cleanly by subclassing UITextField.
Use the textField Delegate,
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
textField=nil;
return NO;
}
swift 3.0 version
First set the delegate for the text field
self.textfield.delegate = self
Then in an extension
extension ViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return false
}
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
// Here you can do for Specific text Field by
if (textField==(the text field you don't want to show keyboard)) {
NSLog(#"don't show keyboard");
return NO;
}
else {
return YES;
}
}
Swift 3/4
Add:- UITextFieldDelegate in your class.
Add:- self.textField.delegate = self In ViewDidLoad
last one just add this func -
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return false
}

Resources