IOS - How to reuse a UIView in different UITableViewCell

advertisements

I am working on a UItableViewController, where there can be five types of UITableViewCell. A major part of each type of cell is common. I can implement these part for all five cells but I would like to make a reusable view and use it inside all the cells. What is the best way to design and implement this requirement?

For example, In Facebook feed, there can be many types of posts. But the like/comment/share panel at the bottom of each post is same. How can I implement these different types of cells keeping like/comment/share panel in a single place on Xcode.

Thanks in advance


Using storyboard

What you can do is subclass the UIView that will contain all the common features.

For example:

class ViewWithBorder : UIView{

   //any view that you apply this class on in storyboard will
   //have the following properties assigned to it
    override func awakeFromNib() {

        super.awakeFromNib()

        self.layer.borderColor = UIColor.blue.cgColor

        self.layer.borderWidth = 1.0

       //programmatically add buttons and whatever you desire to this view here
    }
}

Now in your storyboard, you have a Prototype cell created, just add a UIView inside the cell and set its class to viewWithBorder. All the properties assigned to it in awakeFromNib will be added to that view at run time.

Note: If you create the view programmatically and not using storyboard, you will have to override initWithCoder

OR

Create xib for the new UIView that will be common across all the views and just add it to your cell if its nil in your cellForRow.