如何在UITableViewCell中实现带圆角的阴影?
问题描述:
我想实现投影阴影和圆角在UITableViewCell
。如何在UITableViewCell中实现带圆角的阴影?
- (void)tableView:(UITableView *)tableView willDisplayCell:(MembershipCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
cell.contentView.backgroundColor = [UIColor clearColor];
CGRect rect = cell.frame;
UIView *whiteRoundedCornerView = [[UIView alloc] initWithFrame:CGRectMake(8,8,rect.size.width-8,rect.size.height)];
whiteRoundedCornerView.backgroundColor = [UIColor whiteColor];
whiteRoundedCornerView.layer.masksToBounds = NO;
whiteRoundedCornerView.layer.cornerRadius = 3.0;
whiteRoundedCornerView.layer.shadowOffset = CGSizeMake(0,0);
whiteRoundedCornerView.layer.shadowOpacity = 0.75;
[cell.contentView addSubview:whiteRoundedCornerView];
[cell.contentView sendSubviewToBack:whiteRoundedCornerView];
}
我使用上面的代码,但它显示在单元格的顶部和左侧的阴影。
答
这是因为你没有在右侧和底部有空间,你需要在右侧和底部留出一些空间以显示阴影。此外,您可以将shadowRadius
添加到用于控制阴影半径的图层。尝试以下内容
- (void)tableView:(UITableView *)tableView willDisplayCell:(MembershipCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
cell.contentView.backgroundColor = [UIColor clearColor];
CGRect rect = cell.frame;
UIView *whiteRoundedCornerView;
if (![cell.contentView viewWithTag:SOME_TAG_VALUE]) {
whiteRoundedCornerView = [[UIView alloc] initWithFrame:CGRectMake(8,8,rect.size.width-16,rect.size.height-16)];
whiteRoundedCornerView.backgroundColor = [UIColor whiteColor];
whiteRoundedCornerView.layer.masksToBounds = NO;
whiteRoundedCornerView.layer.cornerRadius = 3.0;
whiteRoundedCornerView.layer.shadowOffset = CGSizeMake(0,0);
whiteRoundedCornerView.layer.shadowOpacity = 0.75;
whiteRoundedCornerView.layer.shadowRadius = 1.0;
whiteRoundedCornerView.tag = SOME_TAG_VALUE;
[cell.contentView addSubview:whiteRoundedCornerView];
}
[cell.contentView sendSubviewToBack:whiteRoundedCornerView];
}
+0
该解决方案是正确的。但是,建议您对单元格进行子类化,并在'awakeFromNib'或'initWithCoder ...'中执行此操作。所以你不要在滚动时创建和添加子视图。我添加了一个粗糙的条件来检查是否已经添加了“whiteRoundedCornerView”。 – n00bProgrammer
+0
我完全同意。 –
没有得到您的问题,但正在寻找'shadowRadius'? – Mahesh