ios – 不能继承WKWebView

我试图继承WKWebView.当我实现自己的初始化程序时,我收到此错误:

'required' initializer 'init(coder:)' must be provided by subclass of 'WKWebView'

好的,众所周知,我们必须为UIView的子类实现它.对于UIView的直接子类,它只是实现它,但使用WKWebView它似乎并不那么简单.我按照Fix-it提示进行了操作,并将此代码段添加到代码中:

required @availability(*, unavailable) convenience init!(coder: NSCoder!) {
        fatalError("init(coder:) has not been implemented")
    }

所以我得到了如下的课程:

import WebKit


class TSWebView : WKWebView {

    let s: String
    let i: Int

    init(s: String, i: Int) {
        self.s = s
        self.i = i
        super.init(frame: CGRectZero, configuration: WKWebViewConfiguration())
    }

    required @availability(*, unavailable) convenience init!(coder: NSCoder!) {
        fatalError("init(coder:) has not been implemented")
    }
}

但是,当我这样做时,我得到以下四个其他错误:

expected declaration
    required @availability(*, unavailable) convenience init!(coder: NSCoder!) {

consecutive declarations on a line must be separated by ';'
    required @availability(*, unavailable) convenience init!(coder: NSCoder!) {

cannot override 'init' which has been marked unavailable
    required @availability(*, unavailable) convenience init!(coder: NSCoder!) {

'required' modifier must be present on all overrides of a required initializer
    required @availability(*, unavailable) convenience init!(coder: NSCoder!) {

有任何想法吗?我的Xcode版本是6.1.1(6A2008a).非常感谢.

最佳答案 这是可能的.您必须仅使用设置了默认值的便捷初始值设定项和属性:

import WebKit
class MPWebView : WKWebView {
    var transparent: Bool = false

    convenience init(config: WKWebViewConfiguration = WKWebViewConfiguration()) {
       let prefs = WKPreferences()
       prefs.plugInsEnabled = true // NPAPI for Flash, Java, Hangouts
       prefs.minimumFontSize = 14
       prefs.javaScriptCanOpenWindowsAutomatically = true;
       config.preferences = prefs
       config.suppressesIncrementalRendering = false
       self.init(frame: CGRectZero, configuration: config)
    }

    convenience required init(url: NSURL) {
       self.init(config: nil)
       loadRequest(NSURLRequest(URL: url))
    }
}
点赞