我编写了自己的 Button、Textfield、...、类。在“自定义类”的 Storyboard中,我将类设置为 UIElement。这非常有效。
现在我需要一个以编程方式添加的工具栏。当我在我的 ViewController 中添加工具栏时,一切都很好。但我想像这样创建自己的工具栏类。
class MyOwnToolbar : UIToolbar {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//never called
self.backgroundColor = UIColor.redColor()
self.tintColor = UIColor.greenColor()
self.barTintColor = UIColor.blueColor()
}
override init(frame: CGRect) {
//error: super.init isn'T called on all paths before returning from initiliazer
}
在我的 ViewController 中,我尝试这样调用:
fromToolBar = MyOwnToolBar() //call nothing?
fromToolBar = MyOwnToolBar(frame: CGRectMake(0,0,0,0)) //doesn't work because init(frame: CGRECT) doesnt work
我的 ViewController 中的旧代码有效:
self.untilToolBar = UIToolbar(frame: CGRectMake(0,0,0,0))
untilToolBar?.backgroundColor = redColor
untilToolBar?.tintColor = greenColor
untilToolBar?.barTintColor = blueColor
所以我可以使用我的工作解决方案,但我想弄清楚为什么我的代码不起作用。所以也许有人有解决方案或好的链接。
最佳答案
这取决于你如何创建你的 MyOwnToolbar
如果你在界面构建器中添加它并将类连接到 UI 元素使用方法 initWithCoder
如果您以编程方式创建 MyOwnToolbar
,则应使用 init
或 initWithFrame
。
例子:
class MyOwnToolbar: UIToolbar {
private func initialize() {
self.backgroundColor = UIColor.redColor()
self.tintColor = UIColor.greenColor()
self.barTintColor = UIColor.blueColor()
}
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
关于swift - 需要初始化?(编码器 aDecoder : NSCoder) not called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39633860/