Austin Berenyi
Austin Berenyi

Reputation: 1053

Why is init(frame: CGRect) not being called in my custom UIView class?

I have a subclass of UIView called GradientView which I'm using in a UITableViewCell

layoutSubviews() is called, but my init method is never called.

import UIKit

class GradientView: UIView {

var gradientLayer = CAGradientLayer()

    override init(frame: CGRect) {

        super.init(frame:frame)

        self.backgroundColor = .orange
        gradientLayer.colors = [UIColor.clear.cgColor, UIColor.black.cgColor]
        gradientLayer.locations = [0.6, 1.0]
        gradientLayer.frame = self.bounds
        self.layer.insertSublayer(gradientLayer, at: 0)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        self.gradientLayer.frame = self.bounds
    }

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

}

What am I missing?

Upvotes: 0

Views: 770

Answers (1)

EmilioPelaez
EmilioPelaez

Reputation: 19892

UITableViewCell is not usually initialized with init(frame:), it's initialized with either init(style: UITableViewCellStyle, reuseIdentifier: String?) or required init?(coder aDecoder: NSCoder).

The first one will be used when you register a class with your table view, and the second one will be used when it's initialized from a storyboard or when you register a xib file with your table view.

Upvotes: 1

Related Questions