2016-09-22 39 views
2

我写了我自己的Button,Textfield,...类。在“自定义类”的故事板中,我将该类设置为UIElement。这工作得很好。需要的init?(编码器aDecoder:NSCoder)不叫

现在我需要一个以编程方式添加的工具栏。当我在我的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 

所以,我可以用我的工作的解决方案,但我想解开为什么我的代码无法正常工作。所以也许有人有解决方案或良好的联系。

+0

你需要定制awakeFromNib方法 –

+0

http://stackoverflow.com/a/29783546/2303865内 –

回答

4

这取决于你如何创建你MyOwnToolbar如果添加此接口建设者和连接类的UI元素的使用方法initWithCoder

如果您建立MyOwnToolbar编程,你应该使用initinitWithFrame

例子:

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

奥列格了它的权利,如果你使用故事板或XIB创建您的视图控制器,然后init?(coder aDecoder: NSCoder)将被调用。

但是,您正在编程构建您的视图控制器,因此将调用init(frame: CGRect)而不是init?(coder aDecoder: NSCoder)

你应该重写init(frame: CGRect)

override init(frame: CGRect) { 
    super.init(frame: frame) 
    self.backgroundColor = UIColor.redColor() 
    self.tintColor = UIColor.greenColor() 
    self.barTintColor = UIColor.blueColor() 
}