在Swift中覆盖多个重载的init()方法
发布时间:2020-12-14 04:45:04 所属栏目:百科 来源:网络整理
导读:我正在尝试使用以下代码在 Swift(Xcode Beta 5)中创建自定义NSTextFieldCell子类: class CustomHighlightTextFieldCell : NSTextFieldCell { required init(coder aCoder: NSCoder!) { super.init(coder: aCoder) } init(imageCell anImage: NSImage!) { su
我正在尝试使用以下代码在
Swift(Xcode Beta 5)中创建自定义NSTextFieldCell子类:
class CustomHighlightTextFieldCell : NSTextFieldCell { required init(coder aCoder: NSCoder!) { super.init(coder: aCoder) } init(imageCell anImage: NSImage!) { super.init(imageCell: anImage) } init(textCell aString: String!) { super.init(textCell: aString) } } 但是,我在第2和第3个init()声明上收到编译错误: /Users/Craig/projects/.../CustomHighlightTextFieldCell:8:40: Invalid redeclaration of 'init(imageCell:)' /Users/Craig/projects/.../CustomHighlightTextFieldCell.swift:17:5: 'init(imageCell:)' previously declared here /Users/Craig/projects/.../CustomHighlightTextFieldCell:7:39: Invalid redeclaration of 'init(textCell:)' /Users/Craig/projects/.../CustomHighlightTextFieldCell.swift:21:5: 'init(textCell:)' previously declared here 虽然这里有一些奇怪的编译器错误(我得到通常的“SourceKitService终止,编辑器功能暂时限制.”消息),似乎我在我的方法覆盖中遗漏了一些东西 – 但我不知道是什么. 我假设命名参数,或者至少是参数类型,表明这里有三种不同的init()方法,但显然我错过了这个谜题的关键部分. 编辑:如果我将覆盖添加到第二和第三个init()方法,我有一个单独的问题: required init(coder aCoder: NSCoder!) { super.init(coder: aCoder) } override init(imageCell anImage: NSImage!) { super.init(imageCell: anImage) } override init(textCell aString: String!) { super.init(textCell: aString) } 这个新问题(仅通过添加两个覆盖关键字来调用)似乎几乎与原始问题相矛盾. /Users/Craig/projects/.../CustomHighlightTextFieldCell.swift:17:14: Initializer does not override a designated initializer from its superclass /Users/Craig/projects/.../CustomHighlightTextFieldCell.swift:21:14: Initializer does not override a designated initializer from its superclass 解决方法
看起来你的声明(使用覆盖)应该足够了,但是,它们似乎也需要@objc声明.这有效:
class CustomHighlightTextFieldCell : NSTextFieldCell { required init(coder aCoder: NSCoder!) { super.init(coder: aCoder) } @objc(initImageCell:) override init(imageCell anImage: NSImage!) { super.init(imageCell: anImage) } @objc(initTextCell:) override init(textCell aString: String!) { super.init(textCell: aString) } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |