From 5425039ff4f6d2475b497fdda7cd3c8d2c11aa66 Mon Sep 17 00:00:00 2001 From: Tom Date: Mon, 19 Nov 2018 20:21:36 +1000 Subject: [PATCH] feat(WKWebview): Add fix for keyboard dismiss leaving viewport shifted in iOS 12 (#134) --- ios/RNCWKWebView.m | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/ios/RNCWKWebView.m b/ios/RNCWKWebView.m index b2c6b39..cf0a311 100644 --- a/ios/RNCWKWebView.m +++ b/ios/RNCWKWebView.m @@ -11,6 +11,7 @@ #import "objc/runtime.h" +static NSTimer *keyboardTimer; static NSString *const MessageHanderName = @"ReactNative"; // runtime trick to remove WKWebView keyboard default toolbar @@ -74,6 +75,19 @@ static NSString *const MessageHanderName = @"ReactNative"; _automaticallyAdjustContentInsets = YES; _contentInset = UIEdgeInsetsZero; } + + // Workaround for a keyboard dismissal bug present in iOS 12 + // https://openradar.appspot.com/radar?id=5018321736957952 + if (@available(iOS 12.0, *)) { + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(keyboardWillHide) + name:UIKeyboardWillHideNotification object:nil]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(keyboardWillShow) + name:UIKeyboardWillShowNotification object:nil]; + } return self; } @@ -122,6 +136,25 @@ static NSString *const MessageHanderName = @"ReactNative"; } } +-(void)keyboardWillHide +{ + keyboardTimer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(keyboardDisplacementFix) userInfo:nil repeats:false]; + [[NSRunLoop mainRunLoop] addTimer:keyboardTimer forMode:NSRunLoopCommonModes]; +} +-(void)keyboardWillShow +{ + if (keyboardTimer != nil) { + [keyboardTimer invalidate]; + } +} +-(void)keyboardDisplacementFix +{ + // https://stackoverflow.com/a/9637807/824966 + [UIView animateWithDuration:.25 animations:^{ + self.webView.scrollView.contentOffset = CGPointMake(0, 0); + }]; +} + - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ if ([keyPath isEqual:@"estimatedProgress"] && object == self.webView) { if(_onLoadingProgress){