2016-07-05 65 views
0

我想實現投影陰影和圓角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]; 
} 

我使用上面的代碼,但它顯示在單元格的頂部和左側的陰影。

+0

沒有得到您的問題,但正在尋找'shadowRadius'? – Mahesh

回答

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]; 
} 
+0

該解決方案是正確的。但是,建議您對單元格進行子類化,並在'awakeFromNib'或'initWithCoder ...'中執行此操作。所以你不要在滾動時創建和添加子視圖。我添加了一個粗糙的條件來檢查是否已經添加了「whiteRoundedCornerView」。 – n00bProgrammer

+0

我完全同意。 –