【问题标题】:Correct calling init function in Apple Swift 5 subclass in Cocoa application在 Cocoa 应用程序的 Apple Swift 5 子类中正确调用 init 函数
【发布时间】:2020-06-08 07:01:31
【问题描述】:

我无法确定在名为 HyperlinkTextField 的子类中调用 NSTextField 的 init 函数的正确格式。

class HyperlinkTextField: NSTextField {
    var url: String = ""

    override func mouseDown(with event: NSEvent) {
        NSWorkspace.shared.open(URL(string: url)!)
    }

    required init?(coder: NSCoder) {  
        super.init(coder: coder)  
        isBezeled = false
    }  

    init(string: String) {
        super.init(string: string) // error: must call a designated initializer of the superclass 'NSTextField'
        isBezeled = false
    }
}

【问题讨论】:

    标签: swift cocoa subclass


    【解决方案1】:

    NSControl 继承的所有类都有两个指定的初始化器

    1. init?(coder: NSCoder)
    2. init(frame: NSRect)

    所以你必须调用后者

    init(string: String) {
        super.init(frame: .zero)
        self.stringValue = string
        isBezeled = false
    }
    

    【讨论】:

    • 为什么在init中调用'isBezeled = false'没有效果?创建一个新函数来初始化变量是可行的。
    猜你喜欢
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    • 2012-10-19
    • 1970-01-01
    相关资源
    最近更新 更多