9

I have coded a custom UIButton as :

 class AccountOpeningButton: UIButton {
  required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        ......
   }
}

I am able to instantiate this Class successfully using my Storyboard. Now, i made a UIView & want to add this button in my UIView as :

var customView:UIView = UIView()
customView.frame = CGRect(x: 0, y: 0, width: 350, height: 250)
.....
let fromDateBtn:UIButton = AccountOpeningButton()//Error comes here as  : Missing Argument for parameter ‘coder’ in call
customView.addSubview(fromDateBtn)

So please help in in reusing this code dynamically also.

P.S. : I referred http://napora.org/nscoder-and-swift-initialization/ Fatal error: use of unimplemented initializer 'init(coder:)' for class Class does not implement its superclass's required members But didn't succeed.

======================================================================= TRIED

let fromDateBtn:UIButton = UIButton() as! AccountOpeningButton

This throws CastException Could not cast value of type 'UIButton' to '.AccountOpeningButton'

1 Answer 1

10

Replace This line

let fromDateBtn:UIButton = AccountOpeningButton()

With This:

let fromDateBtn = AccountOpeningButton()

And add this method in your class

override init(frame: CGRect) {
        super.init(frame: frame)
    }

You can have more than one init method, but you have to obey the inheritance and hierarchy rules. And you need to definitely understand what are called convenience initializers.

For more details find Here

Sign up to request clarification or add additional context in comments.

1 Comment

Accept the answer. (Click the check mark.) up voting is optional. Accepting the correct answer is not.

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.