3

In my iOS app, I've UITextfield at the bottom of the view. So, when user starts entering text, I'm sliding the view up so that users can see what they are typing.
While entering text, view moves upwards, then press home button and the app goes to background.
Now tap on the icon of the app and it brings the app to foreground
Now I noticed that view comes back to original position (X=0, Y=0) but keyboard is still visible.
How to hide the keyboard when the app comes to foreground.

I tried to hide the keyboard in viewWillAppear and viewWillDisappear. It didn't work.

Satyam
  • 15,493
  • 31
  • 131
  • 244

3 Answers3

3
 -(void)applicationDidEnterBackground:(UIApplication *)application
  {
       [self.window endEditing:YES];
  }

********** OR ************

you have to call Notification when you come from background. when you enter from background to foreground then calling this method of appdelegate.

- (void)applicationWillEnterForeground:(UIApplication *)application

fire the notification in it as below.

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"HIDE" object:self];
}

Add notification in your viewcontroller as below

-(IBAction)HideKeyBard:(NSNotification *)noty
{
    [txt resignFirstResponder];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(HideKeyBard:) name:@"HIDE" object:nil];
}

OutPut:

enter image description here

Kirit Modi
  • 23,155
  • 15
  • 89
  • 112
  • Its working good, except minor issue. My text field is at the bottom and so I'm moving the view upwards. My view has a background image. Now when the app comes to foreground, it shows white space at the bottom (where keyboard was shown earlier) – Satyam Oct 16 '14 at 13:47
1
  • Have a weak reference of UIView * in your App Delegate.
  • Set it to whichever text field you show (from any view controller).

When the app comes to foreground, just call resignFirstResponder of the view and it will dismiss the keyboard. This solution does not care which view controller was displayed when the app went to background. All it needs to know is if there was a text view displayed and if yes, just resign it as first responder. If there was nothing displayed this variable will be nil and will be just a no-op.

Now, even if the same view controller is brought to front, the user has to just tap the text view to get the keyboard back which is perfectly acceptable.

Deepak G M
  • 1,650
  • 17
  • 12
1

The best way is to put window?.endEditing(true) in applicationWillResignActive on AppDelegate:

func applicationWillResignActive(_ application: UIApplication) {
window?.endEditing(true)}

hope this help you

Fabio
  • 5,432
  • 4
  • 22
  • 24