1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

WKWebViewの完了ボタンを消した話

Posted at
donebutton.png これのこと WebView内で入力が必要になったときに自動的についてくるらしい、タップするとキーボードを閉じてくれるが、この手のボタンはカスタムで配置するので邪魔だったので消せるようにした やり方は以下
//
//  WKWebView+removeDone.swift
//  WebViewDone

import Foundation
import WebKit

extension WKWebView {
    func removeDoneButton() {
        guard let target = scrollView.subviews.first(where: {
            String(describing: type(of: $0)).hasPrefix("WKContent")
        }), let superclass = target.superclass else {
            return
        }

        let noInputAccessoryViewClassName = "\(superclass)_NoInputAccessoryView"
        var newClass: AnyClass? = NSClassFromString(noInputAccessoryViewClassName)

        if newClass == nil, let targetClass = object_getClass(target), let classNameCString = noInputAccessoryViewClassName.cString(using: .ascii) {
            newClass = objc_allocateClassPair(targetClass, classNameCString, 0)

            if let newClass = newClass {
                objc_registerClassPair(newClass)
            }
        }

        guard let noInputAccessoryClass = newClass, let originalMethod = class_getInstanceMethod(NoInputAccessoryView.self, #selector(getter: NoInputAccessoryView.inputAccessoryView)) else {
            return
        }
        class_addMethod(noInputAccessoryClass.self, #selector(getter: NoInputAccessoryView.inputAccessoryView), method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
        object_setClass(target, noInputAccessoryClass)
    }
}

fileprivate final class NoInputAccessoryView: NSObject {
    @objc var inputAccessoryView: AnyObject? { return nil }
}

WKWebViewにinputAccessoryViewプロパティがあるがread-onlyなため、自分で作ったNoInputAccessoryViewにSwizzleする感じ
あとはWebViewから呼ぶだけ

webView.removeDoneButton()
remove.png

消えた。あとはOSのアップデート等でこの辺が変更にならないことを祈るのみ。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?