12

在 iOS7 中,我们看到了UIKeyboardAppearance的引入。应用于 时效果很好UITextView,但正如Apple 所说UIWebView不符合UITextInputTraits协议。

虽然 UIWebView 类不直接支持 UITextInputTraits 协议,但是你可以为文本输入元素配置一些键盘属性。例如,您可以在输入元素的定义中包含自动更正和自动大写属性以指定键盘的行为,如下例所示。

有没有人想出为键盘外观设置的神奇 HTML 属性?还是没有?任何解决方法?(请不要使用私有 API)

4

1 回答 1

11

一个非常简单的解决方案是- (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
于 2014-04-30T21:39:25.327 回答