无法继承WKWebView

时间:2014-12-15 15:46:30

标签: ios swift subclass init 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)。非常感谢。

2 个答案:

答案 0 :(得分:0)

尝试取出额外的装饰品:

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

虽然我在猜测"可用性(*,不可用)"的全部要点。是为了使你不能调用初始化器(因此不能有效地将WKWebView子类化。

答案 1 :(得分:0)

只需重写常规初始化即可。这对我有效,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")
}