Programmatically focus on a form in a webview (WKWebView)

前端 未结 6 1331
说谎
说谎 2020-12-09 03:50

It\'s possible with UIWebView with following:

[webView setKeyboardDisplayRequiresUserAction:NO]
Call some JS function

How can you do the sa

6条回答
  •  暖寄归人
    2020-12-09 04:27

    This Swift extension does the job and is compatible with 11.3 as well as earlier point releases.

    import Foundation
    import WebKit
    
    typealias OlderClosureType =  @convention(c) (Any, Selector, UnsafeRawPointer, Bool, Bool, Any?) -> Void
    typealias NewerClosureType =  @convention(c) (Any, Selector, UnsafeRawPointer, Bool, Bool, Bool, Any?) -> Void
    
    extension WKWebView{
    
        var keyboardDisplayRequiresUserAction: Bool? {
            get {
                return self.keyboardDisplayRequiresUserAction
            }
            set {
                self.setKeyboardRequiresUserInteraction(newValue ?? true)
            }
        }
    
        func setKeyboardRequiresUserInteraction( _ value: Bool) {
    
            guard
                let WKContentViewClass: AnyClass = NSClassFromString("WKContentView") else {
                    print("Cannot find the WKContentView class")
                    return
            }
    
            let olderSelector: Selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:userObject:")
            let newerSelector: Selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:changingActivityState:userObject:")
    
            if let method = class_getInstanceMethod(WKContentViewClass, olderSelector) {
    
                let originalImp: IMP = method_getImplementation(method)
                let original: OlderClosureType = unsafeBitCast(originalImp, to: OlderClosureType.self)
                let block : @convention(block) (Any, UnsafeRawPointer, Bool, Bool, Any?) -> Void = { (me, arg0, arg1, arg2, arg3) in
                    original(me, olderSelector, arg0, !value, arg2, arg3)
                }
                let imp: IMP = imp_implementationWithBlock(block)
                method_setImplementation(method, imp)
            }
    
            if let method = class_getInstanceMethod(WKContentViewClass, newerSelector) {
    
                let originalImp: IMP = method_getImplementation(method)
                let original: NewerClosureType = unsafeBitCast(originalImp, to: NewerClosureType.self)
                let block : @convention(block) (Any, UnsafeRawPointer, Bool, Bool, Bool, Any?) -> Void = { (me, arg0, arg1, arg2, arg3, arg4) in
                    original(me, newerSelector, arg0, !value, arg2, arg3, arg4)
                }
                let imp: IMP = imp_implementationWithBlock(block)
                method_setImplementation(method, imp)
            }
    
        }
    
    }
    

提交回复
热议问题