我正在使用CALayer将阴影应用于UITableViewCell。

这是我的代码:

- (void)addShadowToView:(UIView *)view
{
    // shadow
    view.layer.shadowColor = [[UIColor colorWithWhite:0.0f alpha:0.1f] CGColor];
    view.layer.shadowOpacity = 1.0f;
    view.layer.shadowOffset = CGSizeMake(0.0f, 3.0f);
    view.layer.shadowRadius = 6.0f;

    CGRect shadowFrame = view.layer.bounds;
    CGPathRef shadowPath = [UIBezierPath bezierPathWithRect:shadowFrame].CGPath;
    view.layer.shadowPath = shadowPath;
}

问题在于,对于某些tableviewcells,阴影不会跨越单元格的整个宽度。对于某些单元,这将是正确的,对于其他单元,则将是错误的。我确实注意到设备的旋转也会对其产生影响,并且重新加载tableview数据有时可以解决该问题。

缓解此问题的最佳方法是什么(用这种方法,我并不是要在每次旋转时重新加载整个tableview等)?

正确应用阴影的单元格底部示例:
ios - UITableViewCell中的CALayer阴影绘制不正确-LMLPHP

向下滚动后,同一表 View 中单元格的底部(阴影仅适用于宽度的前75%):
ios - UITableViewCell中的CALayer阴影绘制不正确-LMLPHP

编辑:我已经注意到问题是由以下几行代码引起的:
CGRect shadowFrame = view.layer.bounds;
CGPathRef shadowPath = [UIBezierPath bezierPathWithRect:shadowFrame].CGPath;
view.layer.shadowPath = shadowPath;

如果我把它们排除在外,一切都很好。但是有人告诉我,使用此功能有一定的性能优势。旋转后,阴影以某种方式未正确地应用于新尺寸。

最佳答案

您可以为单元格的框架覆盖 setter ,并调用addShadowToView:。您可以通过存储单元格的大小并仅在大小更改时才更新阴影路径来进行更多优化,例如:

@property (nonatomic, assign) CGSize size;


- (void) setFrame:(CGRect)frame
{
    [super setFrame:frame];
    // Need to check make sure this subview has been initialized
    if(self.subviewThatNeedsShadow != nil && !CGSizeEqualToSize(self.size,_frame.size)
    {
        [self addShadowToView: self.subviewThatNeedsShadow];
    }
}

07-28 03:45
查看更多