2

I wrote my own Button,Textfield, ..., classes. In the storyboard in "Custom Class" I set the class to the UIElement. This works very well.

Now I needed a toolbar that is added programatically. When I add the Toolbar in my ViewController everything is fine. But I want to create my own toolbar class like this.

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
}

In my ViewController I try to call like this:

fromToolBar = MyOwnToolBar() //call nothing?
fromToolBar = MyOwnToolBar(frame: CGRectMake(0,0,0,0)) //doesn't work because init(frame: CGRECT) doesnt work

Old code in my ViewController that worked:

    self.untilToolBar = UIToolbar(frame: CGRectMake(0,0,0,0))
    untilToolBar?.backgroundColor = redColor
    untilToolBar?.tintColor = greenColor
    untilToolBar?.barTintColor = blueColor

So I could use my working solution, but I want to unterstand why my code isn't working. So maybe somebody have a solution or good links.

2

2 Answers 2

6

It is depending how do you create you're MyOwnToolbar if you add this in interface builder and connect class to the UI element use method initWithCoder

If you're creating your MyOwnToolbar programmatically, you should use init or initWithFrame.

Example:

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")
     }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Oleg got it right, if you use storyboard or a xib to create your view controller, then init?(coder aDecoder: NSCoder) will be called.

But you are building your view controller programmatically, so init(frame: CGRect) will be called instead of init?(coder aDecoder: NSCoder).

you should override init(frame: CGRect):

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.