首页 > 解决方案 > 为什么在我的自定义 UIView 类中没有调用 init(frame: CGRect)?

问题描述

我有一个UIView被调用的子类,GradientView我在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)
    }

}

我错过了什么?

标签: iosswiftuitableviewuiviewsubclass

解决方案


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

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


推荐阅读