uikeyboard return - iphone

I have one view name:myplay.h and myplay.m
my view contain one textfield name txtplay..
It contain one button name btnplay.
In button event i want to check that if uikeyboard is open then close it.
I know below code
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return TRUE;
}
and in button click event
-(IBAction)btnplayclick:(id)sender
{
[self.txtplay resignFirstResponder];
....
....
}
I want a global code to resign.

Try this:
[self.view endEditing:YES];
From the doc:
endEditing:
Causes the view (or one of its embedded text fields) to resign the first responder status.
(BOOL)endEditing:(BOOL)force
This method looks at the current view and its subview hierarchy for the text field that is currently the first responder. If it finds one, it asks that text field to resign as first responder. If the force parameter is set to YES, the text field is never even asked; it is forced to resign.
Available in iOS 2.0 and later.

The best way i think to be generic and reuse your code anywhere is to create a category for the UIView :
#implementation UIView (FindFirstResponder)
- (UIView *)findFirstResonder
{
if (self.isFirstResponder) {
return self;
}
for (UIView *subView in self.subviews) {
UIView *firstResponder = [subView findFirstResonder];
if (firstResponder != nil) {
return firstResponder;
}
}
return nil;
}
#end
And then to call the method like that :
-(IBAction)btnplayclick:(id)sender
{
UIView *firstResponder = [self.view findFirstResonder];
[firstResponder resignFirstResponder];
}
It does the tricks perfectly for me.

or just write
[self.view findAndResignFirstResponder];

Calling resignFirstResponder on a UITextField that ISN'T first responder is a harmless no-op.
So go:
for (UIView *candidate in self.subview) {
if ([candidate isKindOfClass:[UITextView class]]) {
[(UITextView *)candidate resignFirstResponder];
}
}

Related

Hide keyboard on ViewWillAppear

i have a screen having navigation controller and text field. when i move next and come back i want the keyboard should be hidden in first screen. I am hiding keyboard like on textfield event.
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
But how to do that in View related events so that whenever my view appears keyboard is hidden..
Pls guide/Help.
thanks in adv.
I think this is also a good way to remove keyboard with in iOS App if your UITextView or UITextField not connected through the IBOutlet.
If you want to Hide Keyboard with UIViewController LifeCycle Events like with viewWillAppear or etc. Follow this
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[self view] endEditing:YES];
}
Otherwise if you object connected using IBOutLet this code will work fine as you describe too.
[yourTextField resignFirstResponder];
Add this code to your ViewWillAppear :
for(id obj in self.view.subviews)
{
if([obj isKindOfClass:[UITextField class]])
{
[obj resignFirstResponder];
}
}
This would take in all the textfields in that particular view here it is the whole view and add the code you had written previously for removing the keyboard.
A good habit is to write this code in your screen's -viewWillDisappear. So, when you navigate from one screen to another at that time it will remove the keyboard from that screen.
- (void)viewWillDisappear:(BOOL)animated
{
[self.view endEditing:YES];
[super viewWillDisappear:animated];
}
For multiple textFields, it is better to use -endEditing for that particular view instead of -resignFirstResponder for any single textField. Take a look at my Answer.
//This is for Swift
override func viewWillAppear(animated: Bool)
{
self.view.endEditing(true)
}
The thing that you are doing wrong is , when you are moving back previous controller to the current controller , the keyboard is up due to the selected textfield of previous controller .
And in the current controller the code:
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[self view] endEditing:YES];
}
It will not work as no textfield is selected at this controller. So what you need to do is write the same code in the previous controller viewWillDisappear Method it will surely resolve your Problem .
- (void)viewWillDisappear:(BOOL)animated
{
[self.view endEditing:YES];
[super viewWillDisappear:animated];
}

UITextField strange behaviour on resignFirstResponder

Already the second day and cannot figure out the problem,
I've UITabelView with Custom UICellViews, each custom UICellView consists of UILabel and UITextField.
Custom UICellView object allocs UITextField and UILabel in its init method and are released in dealloc.
The number of custom UICellViews in UITableView is 6.
The user scenario is following
When user clicks from from 1 to 5 UITextFields virtual keyboard opens and user types some text
When user clicks on the 6th UITextField if virtual keyboard is active, it should be hidden, and if it is hidden it shall not be displayed.
As implement UITextFieldDelegate protocol in my UIViewController class and set the delegate of each UITextField to self.
My delegate methods are following
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if (textField.tag != 6) {
return YES;
} else {
[textField resignFirstResponder];
return NO;
}
}
-(BOOL) textFieldShouldEndEditing:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
-(void) textFieldDidBeginEditing:(UITextField *)textField {
/* Some code */
}
-(void) textFieldDidEndEditing:(UITextField *)textField
{
[textField resignFirstResponder];
}
All the functions are properly !
So now, the virtual keyboard is never get hidden, why this happens ?
PS. Similar code has worked on iPhone but this issue exists on iPad.
You need to know which textfield was last used! so you can do [lastUsedTextField resignFirstResponder]
There is a dirty, but working trick.. you can make your textfield the new active UITextField and call resignFirstResponder in the next cycle immediately:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if (textField.tag != 6) {
return YES;
} else {
// this will schedule keyboard dismissal for the current text field
dispatch_async(dispatch_get_main_queue(), ^{
[textField resignFirstResponder];
});
return YES; // -> make this one active
}
}
did you seted action for textField?
[YourTextField addTarget:self action:#selector(textFieldDoneEditing:) forControlEvents:UIControlEventEditingDidEndOnExit];
PS set any selector for any ControlEvent

keyboard is not getting dismissed on UITextField

This may sound a newbie question, however I'm new to iOS dev.
Platform : iPad
I have a UITableView with UITextField, let say they are two.
When pressing on the first one virtual keyboard should appear, but when user tapps on the second UITextField the virtual keyboard should be hidden and data picker view should be displayed.
So here it is, how I did it.
-(void) textFieldDidBeginEditing:(UITextField *)textField {
if (textField.tag == PICKER_VIEW_TAG) {
[textField resignFirstResponder];
} else {
...
}
}
-(void) textFieldDidEndEditing:(UITextField *)textField
{
if (textField.tag != PICKER_VIEW_TAG) {
...
}
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if (textField.tag == PICKER_VIEW_TAG) {
[self countriesPickerView];
}
return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField.tag == PICKER_VIEW_TAG) {
[textField resignFirstResponder];
} else {
...
}
return YES;
}
So now the question, when I click for the first time on the first UITextField it displays keyboard, but when I switch to second one it does not hide it. Why ? and how to solve this ?
UPDATE : The corresponding textField is not getting selected but i.e. the resign takes place, right ? but the keyboard is not hidden ... why this happens ?
The issue is with your textFieldShouldReturn. If you want it to complete the action, allow it to return while resigning the first responder.
[textField resignFirstResponder];
return YES;
Set the inputView property on UITextField to display views other than keyboard to receive input. In this case, you would set the text field's inputView to be an instance of UIDatePicker. The picker will be displayed with the same keyboard animation automatically and you get to delete a bunch of code. Win/win.

Resigning First Responder for multiple UITextFields

There is an application in which I am generating multiple UITextFields dynamically. I want to resign first responder whenever the UITextFields are not selected (touch outside the UITextField). How can I know that of which UITextField I have to resign first responder? Please specify any other way beyond the 'tag' concept because I have tried that. Please suggest the right direction. Thanks in advance.
Don't call resignFirstResponder; call endEditing:!
Call endEditing: on any view above the text fields in the view hierarchy. It will locate the first responder and ask it to resign. Use endEditing:YES to force it or endEditing:NO to let the text field's delegate decide if it should end editing (useful if you are validating input).
**[self.view endEditing:TRUE];** //Resign firstresponder for all textboxes on the view
You can implement delegate method
- (void)textFieldDidBeginEditing:(UITextField *)textField;
in that you can take currentTextField = textField;
in another delegate method
- (BOOL)textFieldShouldReturn:(UITextField *)textField;
you can do currentTextField = nil;
you can then resign currentTextField....
use this code and implement
-(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.
}
You can try it like this:
- (void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event {
for (id textField in self.view.subviews) {
if ([textField isKindOfClass:[UITextField class]] && [textField isFirstResponder]) {
[textField resignFirstResponder];
}
}
}
I didn't try it but it seems a good solution
The most generic way and also the only one that worked for me in an UITableViewController was sending the action down the responder-chain and wait for the right object to receive the action:
[[UIApplication sharedApplication] sendAction:#selector(resignFirstResponder) to:nil from:nil forEvent:nil];
Tested in iOS8
You can set textFields as properties and synthesize them. You will need as many properties as you are using in your app.
You can have #synthesise myTextField0, myTextField1, myTextField2; for three textFields. Just assign each UITextField you are using to these properties, while declaring them.
And when you want to resign them, just use [self.myTextField0 resignFirstResponder] at textFieldDidEndEditing or which ever function you want to resign them. And you can use this for other textFields also. This is the way to handle multiple textFields
In general, you can skip all these steps, with textField.returnKeyType = UIReturnKeyDone;
if you have a DONE return key, you can just go to the method
- (BOOL) textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return 1;
}
or you can use tags to tag certain textFields and then resign particular ones.
By the way..i have done this in different manner.. Not looking quite a good programming Champ tech but enough to solve my work!!
for(UIView *v in self.view.subviews)
{
if(([v isMemberOfClass:[UITextField class]]==YES) && !(CGRectContainsPoint(v.frame,[[touches anyObject] locationInView:self.View)))
{
v.userInteractionEnabled=NO;
if([v isEditing])
{
[v resignFirstResponder];
}
}
}
you can check with isFirstResponder.
At any point of time only one UIResponder (UITextField in your case) can be firstResonder.
Using [self.view endEditing:YES]; to resignFirstResponder for the current active UITextField.
This worked for me in Xamarin.iOS / Monotouch.
Change the keyboard button to Next, pass the control to the next UITextField and hide the keyboard after the last UITextField.
private void SetShouldReturnDelegates(IEnumerable<UIView> subViewsToScout )
{
foreach (var item in subViewsToScout.Where(item => item.GetType() == typeof (UITextField)))
{
(item as UITextField).ReturnKeyType = UIReturnKeyType.Next;
(item as UITextField).ShouldReturn += (textField) =>
{
nint nextTag = textField.Tag + 1;
var nextResponder = textField.Superview.ViewWithTag(nextTag);
if (null != nextResponder)
nextResponder.BecomeFirstResponder();
else
textField.Superview.EndEditing(true);
//You could also use textField.ResignFirstResponder(); but the above line makes some users happier (e.g. benzado)
return false; // We do not want UITextField to insert line-breaks.
};
}
}
Inside the ViewDidLoad you'll have:
If your TextFields haven't a Tag set it now:
txtField1.Tag = 0;
txtField2.Tag = 1;
txtField3.Tag = 2;
//...
and just the call
SetShouldReturnDelegates(yourViewWithTxtFields.Subviews.ToList());
//If you are not sure of which view contains your fields you can also call it in a safer way:
SetShouldReturnDelegates(txtField1.Superview.Subviews.ToList());
//You can also reuse the same method with different containerViews in case your UITextField are under different views.
I had a problem in Resigning first responder for the selected UITextField from the multiple TextField.
I find out this is working for me after so many different solutions.
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
for (id textField in self.view.subviews) {
if ([textField isKindOfClass:[UITextField class]] && [textField isFirstResponder] && [textField isEqual:_selectedLabel] ) {
[textField resignFirstResponder];
}
}
}
You can use endEditing instead of resignFirstResponder
Try This
[self.view EndEditing:YES]

Remove clear button (grey x) to the right of UISearchBar when cancel button tapped

Right, to begin my question, here's some screenies of the problem already solved by the Spotify app:
Spotify's Step 1: Standard UISearchBar not in editing mode.
Spotify's Step 2: UISearchBar now in editing mode. Search term entered. Cancel button slides in from the right, and the clear button (grey x) appears.
Spotify's Step 3: Cancel button pressed; keyboard slides out and the search bar is no longer in editing mode. Search term remains and the grey x button is now hidden.
At present, the following code fires off when my cancel button is pressed:
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
[searchBar resignFirstResponder];
[searchBar setShowsCancelButton:NO animated:YES];
}
Which results in:
My Step 3: Search bar now not in editing mode. Cancel button and keyboard has slid out. Search term remains but so does the grey x.
So, my question is this: given that -resignFirstResponder (and -endEditing:, FYI) does not hide the grey x button when a search bar has had text entered into it, how does one hide it?
Thanks again, friends.
The problem is that UISearchBar doesn't expose it's text field, and manages the properties on the text field itself. Sometimes, the values of the properties aren't what you want.
For instance, in my own app, I wanted the keyboard style for my search bar to use the transparent alert style.
My solution was to walk through the subviews of the search bar until you find the text field. You should then be able to set the clearButtonMode property, using something like UITextFieldViewModeWhileEditing as a parameter.
This should make it so that the clear button is only shown while the text field is editing.
You want to do this on viewDidLoad or something early, so it's set before you start using it (but after the search bar is initialised.
for (UIView *subview in searchBar.subviews)
{
if ([subview conformsToProtocol:#protocol(UITextInputTraits)])
{
[(UITextField *)subview setClearButtonMode:UITextFieldViewModeWhileEditing];
}
}
Looks like iOS 7 changed the view hierarchy of UISearchBar, and the text box is deeper in the view (The above solution didn't work for me). However, modifying the above solution to traverse the whole hierarchy works:
[self configureSearchBarView:[self searchBar]];
- (void)configureSearchBarView:(UIView*)view {
for (UIView *subview in [view subviews]){
[self configureSearchBarView:subview];
}
if ([view conformsToProtocol:#protocol(UITextInputTraits)]) {
[(UITextField *)view setClearButtonMode:UITextFieldViewModeWhileEditing];
}
}
I'm building upon the previous answers because I started seeing crashes on iOS 7.1 unless I made the following change. I added an additional call to respondsToSelector for each view to make sure that setClearButtonMode: can be called. I observed an instance of UISearchBar getting passed in, which seems to conform to the UITextInputTraits protocol yet does not have the setClearButtonMode: selector, so a crash occurred. An instance of UISearchBarTextField also gets passed in and is the actual object for which to call setClearButtonMode:.
- (void)removeClearButtonFromView:(UIView *)view
{
if (!view)
{
return;
}
for (UIView *subview in view.subviews)
{
[self removeClearButtonFromView:subview];
}
if ([view conformsToProtocol:#protocol(UITextInputTraits)])
{
UITextField *textView = (UITextField *)view;
if ([textView respondsToSelector:#selector(setClearButtonMode:)])
{
[textView setClearButtonMode:UITextFieldViewModeNever];
}
}
}
You need to get the textField of the Search Bar
UITextField *textField = [searchBar valueForKey:#"_searchField"];
textField.clearButtonMode = UITextFieldViewModeNever;
use in - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar method.
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
UITextField *textField = [searchBar valueForKey:#"_searchField"];
textField.clearButtonMode = UITextFieldViewModeNever;
}
A better way to do this in iOS7 is:
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setClearButtonMode:UITextFieldViewModeWhileEditing];
To expand on Jadariens answer if you never want the grey x to appear you need to use the following
for (UIView *subview in searchBar.subviews)
{
if ([subview conformsToProtocol:#protocol(UITextInputTraits)])
{
[(UITextField *)subview setClearButtonMode:UITextFieldViewModeNever];
}
}
Accepted answer does not work on iOS7+, here is the modified version as a Swift extension
extension UIView {
class func removeClearButton(svs: [UIView]) {
for sv in svs {
if let tv = sv as? UITextField where sv.conformsToProtocol(UITextInputTraits) {
tv.clearButtonMode = .Never
return
} else {
UIView.removeClearButton(sv.subviews)
}
}
}
}
Usage
UIView.removeClearButton(searchBar.subviews)
Hers is a category I wrote that does this
Category
#implementation UISearchBar (Additions)
- (void)setClearButtonMode:(UITextFieldViewMode)viewMode {
UITextField *textField = [self findTextFieldInView:self];
[textField setClearButtonMode:viewMode];
}
- (UITextField *)findTextFieldInView:(UIView *)view {
for (UIView *subview in view.subviews) {
if ([subview isKindOfClass:[UITextField class]] ||
[subview.class isSubclassOfClass:[UITextField class]]) {
return (UITextField *)subview;
}
UITextField *textField = [self findTextFieldInView:subview];
if (textField) {
return textField;
}
}
return nil;
}
#end
Usage
[searchBar setClearButtonMode:UITextFieldViewModeWhileEditing];
There's a better way than any of the answers here, and you don't have to use private APIs or traverse subviews to do it.
UISearchBar has a built-in API for doing this:
[UISearchBar setImage:forSearchBarIcon:state]
The SearchBar icon key you want is UISearchBarIconClear, and you want the UIControlStateNormal state. Then give it a clear image for the image, and you're done.
So, it should look like this:
[searchBar setImage:clearImage forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
For the (x) icon in searchBar. You can use below delegate method.
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
searchBar.showsCancelButton = YES;
}
for (UIView *subview in _search_bar.subviews)
{
NSLog(#"%#",subview.subviews);
for (UIView *subview11 in subview.subviews)
{
if ([subview11 conformsToProtocol:#protocol(UITextInputTraits)])
{
[(UITextField *)subview11 setClearButtonMode:UITextFieldViewModeNever];
}
}
}