为什么在我的自定义 UIView class 中没有调用 init(frame: CGRect)?

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

我有一个名为 GradientViewUIView 子类,我在 UITableViewCell

中使用它

layoutSubviews() 被调用,但我的 init 方法从未被调用。

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)
    }

}

我错过了什么?

UITableViewCell 通常不使用 init(frame:) 初始化,它使用 init(style: UITableViewCellStyle, reuseIdentifier: String?)required init?(coder aDecoder: NSCoder).

初始化

第一个将在您使用 table 视图注册 class 时使用,第二个将在从情节提要初始化时或您注册 xib 文件时使用您的 table 视图。