UITextField - Keyboard not hiding when app comes from background

僤鯓⒐⒋嵵緔 提交于 2020-01-25 10:25:06

问题


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.


回答1:


 -(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:




回答2:


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

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

hope this help you




回答3:


  • 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.



来源:https://stackoverflow.com/questions/26399488/uitextfield-keyboard-not-hiding-when-app-comes-from-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!