[UITableViewCell] <- [genericCell] <- [Cell1], [Cell2], [Cell3]
Hello. Please imagine hierarchy above. In my code I don\'t have objects exactly of type gener
This is how I would lay down the hierarchy mentioned by you:
Step 1 : Make Generic Cell class
class GenericCell : UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
print("Generic Cell Initialization Done")
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
Step 2 : Make Specific Cell 1 class:
class MyCell1 : GenericCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
print("MyCell1 Initialization Done")
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
Step 3 : Make Specific Cell 2 class:
class MyCell2 : GenericCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
print("MyCell2 Initialization Done")
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
Step 4 : Make Specific Cell 3 class:
class MyCell3 : GenericCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
print("MyCell3 Initialization Done")
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
Step 5 : Finally use the cells like this:
let cell1 = MyCell1.init(style: UITableViewCellStyle.Default, reuseIdentifier: "cell1")
let cell2 = MyCell2.init(style: UITableViewCellStyle.Default, reuseIdentifier: "cell2")
let cell3 = MyCell3.init(style: UITableViewCellStyle.Default, reuseIdentifier: "cell3")
PS: This would guarantee setting the properties in generic cell as well in specific cells.
EDIT: This is how you would use cells in cellForRowAtIndexPath
:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell1 = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as MyCell1
if cell1 == nil {
cell1 = MyCell1.init(style: UITableViewCellStyle.Default, reuseIdentifier: "cell1")
}
// Do your cell property setting
return cell1
} else if indexPath.section == 1 {
let cell2 = tableView.dequeueReusableCellWithIdentifier("cell2", forIndexPath: indexPath) as MyCell2
if cell2 == nil {
cell2 = MyCell2.init(style: UITableViewCellStyle.Default, reuseIdentifier: "cell2")
}
// Do your cell property setting
return cell2
} else {
let cell3 = tableView.dequeueReusableCellWithIdentifier("cell3", forIndexPath: indexPath) as MyCell3
if cell3 == nil {
cell3 = MyCell3.init(style: UITableViewCellStyle.Default, reuseIdentifier: "cell3")
}
// Do your cell property setting
return cell3
}
}