为类似布局的 UITableViewCell 重用布局代码

Reuse layout code for a UITableViewCell of similar layout

我正在尝试复制内置的 Apple Reminders 应用程序。其中,有两种类型的单元格:一种用于显示提醒项,一种用于添加新项: 我不使用 Interface Builder,因此所有布局代码都包含在 UITableViewCell 子类中。在这里,我为提醒项单元格创建了一个:

class ItemCell: UITableViewCell {
    var leftButton: UIButton!
    var middleLabel: UILabel!

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        middleLabel = UILabel()
        middleLabel.translatesAutoresizingMaskIntoConstraints = false

        leftButton = UIButton(type: .custom)
        leftButton.translatesAutoresizingMaskIntoConstraints = false
        leftButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)

        contentView.addSubview(middleLabel)
        contentView.addSubview(leftButton)

        NSLayoutConstraint.activate([
            leftButton.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8.0),
            leftButton.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
            middleLabel.leadingAnchor.constraint(equalTo: leftButton.trailingAnchor, constant: 8.0),
            middleLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: 8.0),
            middleLabel.centerYAnchor.constraint(equalTo: leftButton.centerYAnchor)
        ])
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

现在,如果我要为添加项单元格创建另一个 UITableViewCell 子类,它的很多布局代码将是相同的,只是子视图的类型不同。复制和粘贴代码片段的最简单解决方案有其明显的缺陷,即不干净、可重用和优雅。

我可以假设更好的解决方案是使用继承、工厂 类 或协议,但很难找到针对此特定任务的最佳实践。

创建一个仅将 UIView 作为参数并创建布局的函数。

然后创建一个派生自 table 单元格的基础 class 并将该函数移到那里。

最后更改此 class 以派生自新基数 class

现在您的新单元格也可以从那个 class 派生。