一个非常简单的解决方案是- (UIKeyboardAppearance) keyboardAppearance
通过类别扩展将方法添加到UIView
. 在这种方法中,您可以简单地返回UIKeyboardAppearanceDark
. 这是有效的,因为该方法会神奇地添加到内部UIWebView
视图(UIWebBrowserView
这种方法的主要问题是它会影响所有 UIView 派生的视图,这可能是不可取的。
我们可以构建一个更有针对性的解决方案,拦截负责键盘的第一响应者,并keyboardAppearance
在不存在时向其添加方法。如果将来更改内部实现UIWebBrowserView
以包含keyboardAppearance
选择器,这将优雅地降级。
#import <objc/runtime.h>
@protocol TSPingPong <NSObject>
- (void) ts_pong: (id) sender;
@end
@interface NSObject (TSPingPong)
@end
@implementation NSObject (TSPingPong)
- (void) ts_ping: (id) sender
{
if ( [sender respondsToSelector: @selector(ts_pong:)] )
{
[sender performSelector: @selector( ts_pong: ) withObject: self ];
}
}
@end
@implementation TSViewController
{
IBOutlet UIWebView* _webView;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(keyboardWillAppear:)
name: UIKeyboardWillShowNotification
object: nil];
NSString* html = @"<br><br><br><form action=''> " \
"First name: <input type='text'><br> " \
"Last name: <input type='text'><br>" \
"<input type='submit' value='Submit'> " \
"</form>";
[_webView loadHTMLString: html
baseURL: nil];
}
- (void) keyboardWillAppear: (NSNotification*) n
{
// the keyboard is about to appear!
// play pingpong with the first responder so we can ensure it has a keyboardAppearance method:
[[UIApplication sharedApplication] sendAction: @selector( ts_ping:) // added via category extension
to: nil // to: the first responder
from: self // "sender"
forEvent: nil];
}
- (void) ts_pong: (id) sender
{
// sender is the first responder. Happens to be undocumented "UIWebBrowserView" in this case.
// if it doesn't have it's own keyboardAppearance method then let's add one:
if ( ![sender respondsToSelector: @selector(keyboardAppearance)] )
{
Method m = class_getInstanceMethod( [self class], @selector( keyboardAppearanceTemplateMethod ) );
IMP imp = method_getImplementation( m );
const char* typeEncoding = method_getTypeEncoding( m );
class_addMethod( [sender class], @selector(keyboardAppearance), imp, typeEncoding );
}
}
- (UIKeyboardAppearance) keyboardAppearanceTemplateMethod
{
return UIKeyboardAppearanceDark;
}
@end