Search code examples
iosuitableviewtableviewcustom-cell

Custom cells with common features in ios


I have an app in which I have a tableview. Inside this tableview I currently have 8 different types of cells. Each of these cells are different but also have similarities.

As an example (using only 2 cells for simplicity). Imagine you have cell 1 which can be divided into 3 parts:

--------------A-------------- --------------B-------------- --------------C--------------

Now cell 2 also has 3 parts. Parts A and C are the same as in cell1 (different data of course, but same structure):

--------------A-------------- --------------D-------------- --------------C--------------

Currently, in my cellForRowAt method I just check if the cell type should be 1 or 2 and then I dequeue cell for that type. The challenge is that I would like to avoid setting part A and C two different places in the code.

Eg. instead of

if type == type1 {
    //Set A
    //Set B
    //Set C
} else if type == type2 {
    //Set A
    //Set D
    //Set C
}

I would like

//Set A
//Set C
if type == type1 {
    //Set B
} else if type == type2 {
    //Set D
}

I was wondering if there is a way to "abstract" these commonalities?

Please let me know if anything is unclear.

EDIT: IB Challenge

I probably should also mention that a tricky part for me is figuring out how a parent cell would fit in in regards to IB. I have separate xib files for each cell type, but if I would only have one parent swift file with section A and C, can both my other xib files have the same outlets to this parent and how would this even be done?


Solution

  • Parent TableViewCell

    class BaseTableViewCell: UITableViewCell {
    
      @IBOutlet weak var ALabel: UILabel!
      @IBOutlet weak var CLabel: UILabel!
    
        override func awakeFromNib() {
            super.awakeFromNib()
            // Initialization code
        }
    
        override func setSelected(_ selected: Bool, animated: Bool) {
            super.setSelected(selected, animated: animated)
            // Configure the view for the selected state
        }
    
    }
    

    Subclass of BaseCell

    class TypeOneTableViewCell: BaseTableViewCell {
    
      @IBOutlet weak var BLabel: UILabel!
    
        override func awakeFromNib() {
            super.awakeFromNib()
            // Initialization code
        }
    
        override func setSelected(_ selected: Bool, animated: Bool) {
            super.setSelected(selected, animated: animated)
    
            // Configure the view for the selected state
        }
    
    }
    

    enter image description here

    enter image description here