我可以使用这个通用配置器 BaseCell 吗?

问题描述 投票:0回答:0

我制定可配置的细胞协议

protocol ViewConfigurable { 
    func setupControls()
    func setupLayout()
}

protocol CellConfigurable: ViewConfigurable {
    static var cellId: String { get } 

    associatedtype Model
    var model: Model? { get } 

    func initData()
    func configure(_ model: Model)
}

和选择

CellConfigurable
协议在
BaseCell

import UIKit

class BaseCell<T>: UICollectionViewCell {  

    static var cellId: String { return String(describing: self) }

    private(set) var model: T?

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupControls()
        setupLayout()
    }

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

    func initData() { } 

    func configure(_ model: T) {
        initData()
        self.model = model
    }

    func setupControls() { }
    func setupLayout() { }
}

extension BaseCell: CellConfigurable { }

例如

struct Person {
                 let id: Int
    private(set) var name: String?
}

BaseCell
模型是
Person

如果使用上述方法, 需要覆盖

BaseCell

中的所有功能
import UIKit

class PersonCell: BaseCell<Person> {

    private var idLabel: UILabel!
    private var nameLabel: UILabel!

    override func initData() {
        idLabel.text = nil
        nameLabel.text = "is empty name"
    }

    override func configure(_ model: Person) {
        super.configure(model) 

        idLabel.text = String(model.id)
        
        if let name = model.name, !name.isEmpty {
            nameLabel.text = name
        }
    }

    override func setupControls() { ... }
    
    override func setupLayout() { ... }

}

不知是不是违反可读性和语言特性的行为

谢谢。

uicollectionviewcell
© www.soinside.com 2019 - 2024. All rights reserved.