Laurent Rivard
Laurent Rivard

Reputation: 519

Best practice to subclass UIKit classes

I'm using Swift, and I find myself having to subclass UIKit classes such as UIView and UIButton. I don't care about setting the frame since I'm using AutoLayout, so I don't want/need to use init(frame: CGRect).

class customSubclass: UIView {
    var logo: UIImage
    init(logo: UIImage) {
       self.logo = logo

       //compiler yells at me since super.init() isn't called before return from initializer

       //so I end up doing this
       super.init(frame: CGRectZero)
       self.translatesAutoresizingMaskIntoConstraints = false
    }

I also don't find it very sexy to set it's frame to CGRectZero.

Is there a way to having a custom initializer for a subclass of a UIView or UIButton without explicitly setting it's frame?

Note Every subclass is instantiated in code, so required init(coder: aDecoder) is in my code, but isn't actually doing anything.

Thanks!

Upvotes: 1

Views: 679

Answers (3)

dbn
dbn

Reputation: 458

During initialization of a subclass, you must call the designated initializer of a superclass. In your case, since you are creating these views programmatically, you must use super.init(frame: CGRect). As you mentioned, it would be useful to implement two designated initializers for your subclass, one of which takes in a frame:CGRect argument.

Please see the accepted answer to this question for a more thorough review.

Upvotes: 1

mccoyLBI
mccoyLBI

Reputation: 171

Instead of creating a new class and subclassing, you could try using extensions.

extension UIView {
    var logo: UIImage = myImage
    func myLogo() {
        // code here
    }
}

Upvotes: 0

NRitH
NRitH

Reputation: 13903

If you're using autolayout in a storyboard or xib, then just override the init(coder:) method so that it calls the superclass's version, and have your convenience initializers pass CGRectZero or some other value in.

Upvotes: 0

Related Questions