7

我正在尝试继承 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)。非常感谢。

4

3 回答 3

4

只需像这样覆盖常规初始化。这对我有用,Swift 5。

override init(frame: CGRect, configuration: WKWebViewConfiguration) {
    super.init(frame: frame, configuration: configuration)
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
于 2019-07-24T05:10:46.880 回答
3

这是可能的。您只能使用设置了默认值的便利初始化程序和属性:

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))
    }
}
于 2015-05-03T03:44:22.013 回答
1

尝试取出多余的装饰品:

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())
    }

    convenience init!(coder: NSCoder!) {
        super.init(coder:coder)
    }
}

尽管我猜测“availablity(*,不可用)”的全部意义在于使您无法调用初始化程序(因此无法有效地继承 WKWebView.

于 2014-12-15T17:20:21.827 回答