Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical space between UITableViewCells after setting the backgroundView on a cell

I am implementing UITableViewCells that have a custom background and expands when tapped.

I am setting a custom view as my UITableViewCells backgroundView: (in RowForIndexPath)

if (cell == nil) {
    CGRect f = CGRectMake(0.0f, 0.0f, 300.0f, 50.0f);

    cell = [[UITableViewCell alloc] initWithFrame:f reuseIdentifier:cellIdentifier];

    UIView *back = [[UIView alloc] initWithFrame:CGRectMake(10.0f, 10.0f, 300.0f, 50.0f)];
    back.layer.cornerRadius = 8.0f;
    [back setBackgroundColor:[UIColor blackColor]];

This works fine, by setting the backgroundView instead of the contentView, my backgroundView scales to accommodate the new size of the cell after it expands (changing the height in heightForRowAtIndexPath after a tap).

My problem is now that I would like a few pixels vertical space between my cells. Using the above approach will make the rounded black cells be displayed "back to back".

Is there a way to add the vertical space between the cells or is there a completely different approach I can take to obtain the desired look of my cells?

Thanks in advance.

like image 384
RickiG Avatar asked Nov 29 '25 15:11

RickiG


1 Answers

In order to display a space between cells and avoid the "back to back" issue that you are having you can add a UIView with the the following frame CGRectMake(0, 0, 320, 1) and the background set to a light gray for the standard cell separator or if you just want some padding you can make the background clear.

Personally I like to use interface builder but you can of course do this programmatically.

UIView *cellSeparator = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320 ,1)];
[cellSeparator setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin |
                                   UIViewAutoresizingFlexibleRightMargin | 
                                   UIViewAutoresizingFlexibleWidth];       
[cellSeparator setContentMode:UIViewContentModeTopLeft];    
[cellSeparator setBackgroundColor:[UIColor lightGrayColor]];
[cell addSubview:cellSeparator];
[cellSeparator release];

The reason I set the cellSeparator at the top of the cell is because the effect is really for the cells that fall in between the first and last rows. Also it is important to set the autoresizingMask and the contentMode to make sure the cell separator adjusts properly when you make size changes to the UITableViewCell. If you have any elements in the cell that start at x=0 y=0 of you will need to move them down the height of the cell separator plus perhaps some additional pixels for padding so that the separator doesn't run through any elements with in the cell.

like image 97
David Rutgos Avatar answered Dec 01 '25 04:12

David Rutgos