10000RubyPools
10000RubyPools

Reputation: 1202

How to Add Margin Between UITableViewCells Without Being Hacky

A lot of the solutions I've seen here include changing the cell's background to an image and using sections for rows rather than just rows themselves. I'm looking to have only two sections and have each cell expand in height on tap, so neither of those solutions would work.

I saw one solution includes setting the frame of the cell in the layoutSubviews() function like so:

    override func layoutSubviews() {
        super.layoutSubviews()

        self.frame = CGRectOffset(self.frame, 0, 10);
    }

When I do this however, it only gives margin to one cell and that's only when I tap on the cell.

Is there a surefire way to add spacing in between UITableViewCells without being hacky and breaking the cell layouts in the process?

Upvotes: 3

Views: 499

Answers (2)

Fred Faust
Fred Faust

Reputation: 6800

I did this yesterday pretty easily with auto layout.

I set the background of the cell and it's content view to clear, then I created a new view and setup constraints all around it and put my labels inside of it. The height changes dynamically based on the label so I needed to use UITableViewAutomaticDimension for the row height and give it an estimated row height as well.

I don't see why this wouldn't work for expanding it on a tap as well, you just might have to reload the cell.

Upvotes: 4

dopcn
dopcn

Reputation: 4218

  1. make the cell and it's contentView transparent
  2. contentView addSubview customContentView and layout your cell on customContentView
  3. customContentView pin to contentView top leading trailing with offset 0 but pin to bottom with offset 10 //the margin height

Upvotes: 1

Related Questions