Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableViewCell shadow disappears after scroll

I have subclassed UITableViewCell class to add shadow below my cell. The shadow is added correctly, when TableView appears on screen. But, when I scroll tableview down, and cell with shadow hides above the screen, the shadow disappears.

- (void)layoutSubviews {
    [super layoutSubviews];
    if (self.shouldAddShadow) {
        self.layer.shadowOpacity = 0.5;
        self.layer.shadowRadius = 1.5;
        self.layer.shadowOffset = CGSizeMake(0, 3);
        self.layer.shadowColor = [[[UIColor appDarkDividerColor] colorWithAlphaComponent:0.9] CGColor];
        [self setClipsToBounds:NO];
        [self.layer setMasksToBounds:NO];
        CGRect shadowFrame = self.layer.bounds;
        CGPathRef shadowPath = [UIBezierPath bezierPathWithRect:shadowFrame].CGPath;
        self.layer.shadowPath = shadowPath;
    }
}

forgot to mention, that i have tableview with static cells; so prepareForReuse isn't called. I have outlets for my cells, so that i've also tried to set the shadow to my cell in scrollViewDidScroll: method. Even this din't help me

like image 219
ilyuha29 Avatar asked Jun 25 '15 10:06

ilyuha29


1 Answers

I just encountered this problem. Finally I find the way to make it work.

It doesn't disappear(removed), it was just been hidden.

There we use a property zPosition of cell's layer.

From Apple docs:

The default value of this property is 0. Changing the value of this property changes the the front-to-back ordering of layers onscreen. This can affect the visibility of layers whose frame rectangles overlap.

The value of this property is measured in points.

The default value is 0. This leads top cell hides the bottom cell (say shadow). It means if you set shadow for a view to make it show in both sides and the margin before two cell is zero, only bottom shadow of the top cell will show up, the top shadow of the bottom shadow will be hidden.

When the cell goes out of the screen and then back, though the zPosition of each cell is still 0, for those cells, bottom cell hides top cell now. The hide direction is opposite to your scroll direction. This is exactly the situation you met.

So,

cell.layer.zPosition = <#value you want#>

For example, I want to show shadow of the siblings, I can set zPosition of this cell's layer to -1, then shadow of both side will appear.

zPosition of a layer decide which cell can show in the front, and which shows in the back. Like z-index in CSS.

So the solution is change the zPosition property to make it work as you expected.


In addition, you should not set cell's clipsToBounds to YES. (default value is NO)

like image 54
ooops Avatar answered Nov 12 '22 07:11

ooops