[英]How to override UIView initializer in Swift 1.0
Swift (1.0) inheritance is driving me nuts beyond believe. 斯威夫特(1.0)的继承让我疯狂无法相信。 I can believe have have to ask something that as simple as this but I can't figure it out. 我可以相信必须要问一些像这样简单但我无法弄明白的事情。 I have my custom view which I want to be able create programmatically with init(frame: CGRect) as well as load it from story board in which case init(coder aDecoder: NSCoder) should be used for initialization. 我有我的自定义视图,我希望能够使用init(frame:CGRect)以编程方式创建,以及从故事板加载它,在这种情况下应该使用init(coder aDecoder:NSCoder)进行初始化。 in both cases I want to call my custom setup method. 在这两种情况下,我想调用我的自定义安装方法。 Like so : 像这样:
import UIKit
class CustomView: UIView {
override convenience init(frame: CGRect) {
super.init(frame: frame)
self.myCustomSetup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.myCustomSetup()
}
func myCustomSetup() {
self.backgroundColor = UIColor.redColor()
}
}
this does not seem to work, from swift documentation I understand there should only be one designated initializer for class which all the convenience initializers call. 这似乎不起作用,从快速文档我明白应该只有一个指定的初始化程序,所有的便利初始化程序调用。 In UIView case this should be init(coder aDecoder: NSCoder). 在UIView的情况下,这应该是init(编码器aDecoder:NSCoder)。 I however can not create aDecoder: NSCoder
in init(frame: CGRect)
neither can I pass nil as its not optional. 但是我无法创建一个aDecoder: NSCoder
init(frame: CGRect)
aDecoder: NSCoder
init(frame: CGRect)
我也不能传递nil,因为它不是可选的。 What should I do ? 我该怎么办 ? How can I override them both ? 我怎样才能覆盖它们?
A class must have at least one designated initializer. 一个类必须至少有一个指定的初始值设定项。 It may have more than one. 它可能不止一个。
All you have to do to make your code work is remove the keyword convenience
from init(frame: CGRect)
. 要使代码工作,您init(frame: CGRect)
从init(frame: CGRect)
删除关键字convenience
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.