如何在UITableViewCell中实现带圆角的阴影?

时间:2016-07-05 11:39:46

标签: ios objective-c uitableview

我想在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];
}

我正在使用上面的代码,但它显示了单元格顶部和左侧的阴影。

1 个答案:

答案 0 :(得分:1)

那是因为你的右边和底部没有空间,你需要在右边和底部留出一些空间以便阴影出现。此外,您可以将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];
}