不要在单元格中使用泛型,而是将UIView
其子类化为一个封装要显示的图标类型的新类。考虑这个例子:
UIView
封装 PaintCode 周围的图标逻辑的子类。注意Option
枚举和@IBDesignable
属性(允许在 中进行实时渲染Interface Builder
):
import UIKit
@IBDesignable class OptionsView: UIView {
// MARK: - Properties
// Allowed options.
enum Option {
case star, tree
}
// Option that should currently be displayed. Default is .star (for no particular reason).
var currentOption: Option = .star {
didSet {
setNeedsDisplay() // Force redrawing.
}
}
// MARK: - Lifecycle
override func draw(_ rect: CGRect) {
drawIcon(rect)
}
}
// MARK: - Private
private extension OptionsView {
/// Logic to decide which icon to display.
func drawIcon(_ rect: CGRect) {
switch currentOption {
case .star:
StyleKit.drawStarIcon(frame: rect)
case .tree:
StyleKit.drawTreeIcon(frame: rect)
}
}
}
故事板配置:自定义UITableViewController
+ 自定义UITableViewCell
与自定义UIView
(注意class
type 的属性OptionsView
):

UILabel
将和连接OptionsView
到您的CustomCell
. 实现示例(注意var option
):
import UIKit
class CustomCell: UITableViewCell {
// MARK: - Public Properties
// Option that should currently be displayed. Default is .star (for no particular reason).
var option: OptionsView.Option = .star {
didSet {
iconView.currentOption = option
updateLabelText()
}
}
// MARK: - Private Properties
@IBOutlet private weak var iconView: OptionsView!
@IBOutlet private weak var label: UILabel!
}
// MARK: - Private
private extension CustomCell {
func updateLabelText() {
switch option {
case .star:
label.text = "Star"
case .tree:
label.text = "Tree"
}
}
}
最后,在您的自定义中UITableViewController
:
import UIKit
class TableViewController: UITableViewController {
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1 // Hardcoded in this example.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 40 // Hardcoded in this example.
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let customCell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as? CustomCell {
// Logic around which option to display
if indexPath.row < 20 {
customCell.option = .star
} else {
customCell.option = .tree
}
return customCell
}
// Fallback.
return UITableViewCell()
}
}
最后结果:

整个代码参考这个项目(第六次测试):
https ://github.com/backslash-f/paintcode-tests