Matt Spoon
Matt Spoon

Reputation: 2830

trouble with init coder function in custom view class

I'm trying to place a view from a custom view class on my main view controller programatically. Here is my code:

import UIKit

class BarControl: UIView {

// MARK: Initialization

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
    button.backgroundColor = UIColor.redColor()
    button.addTarget(self, action: "ratingButtonTapped:", forControlEvents: .TouchDown)
    addSubview(button)

}

override func intrinsicContentSize() -> CGSize {
    return CGSize(width: 240, height: 44)
}


}

And in my main view controller:

 let myView = BarControl()

An error comes up saying "Missing argument for parameter 'coder' in call"

What should I put in the brackets of let myView = BarControl()?

Upvotes: 0

Views: 357

Answers (2)

HMHero
HMHero

Reputation: 2343

When I subclass UIView I always override init(frame: CGRect) and add any additional implementation. Then xcode usually tells you that - ‘required’: initializer ‘init(coder:)’ must be provided by subclass of ‘UIView’ and if you click that error and hit enter it automatically added that extra initializer. Well, I've been doing this without fully understanding why I have to add that extra initializer I never use. And your question finally made me look for the reason. I found a good tutorial about this initializer confusion(?) in the following link.

http://www.edwardhuynh.com/blog/2015/02/16/swift-initializer-confusion/

It's a short article about your confusion(?) =)

Basically the answer for your question is you should override init () to call BarControl() instead of init(coder aDecoder: NSCoder!). In addition, you have to add all the UIView's initializers to use the initializer you want to use according to the article.

Upvotes: 1

user1585121
user1585121

Reputation:

The fonction prototype is looking like this:

required init(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder)
        // Your code here
    }

I dont think you need the optional?

Upvotes: 0

Related Questions