【问题标题】:Reuse layout code for a UITableViewCell of similar layout为类似布局的 UITableViewCell 重用布局代码
【发布时间】:2020-04-28 21:19:00
【问题描述】:

我正在尝试复制内置的 Apple 提醒应用。其中,有两种类型的单元格:一种用于显示提醒项目,另一种用于添加新项目: 我不使用 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 子类,它的许多布局代码将是相同的,只是子视图的类型不同。仅复制和粘贴代码片段的最简单解决方案有其明显的缺陷,即不干净、可重用和优雅。

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

【问题讨论】:

    标签: ios swift uitableview architecture reusability


    【解决方案1】:

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

    然后创建一个从表格单元派生的基类并将该函数移到那里。

    最后把这个类改成从新的基类派生

    现在您的新单元格也可以从该类派生。

    【讨论】:

    • 是否可以有一个只负责创建布局的基类?另外,基类是否需要了解子视图(具体来说,它是否应该具有UIView 属性)?
    • 也许它会变得拥有更多这些细胞共有的东西。仅添加共享代码所需的内容。试一试——你可能需要通过几种方式来查看它
    猜你喜欢
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多