【发布时间】: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