來(lái)源:http://m.itdecent.cn/p/739408a7aae1
給section添加圓角和陰影效果,效果如下:

image.png
全部實(shí)現(xiàn)都在UITableView的willDisplayCell代理方法里:
給每個(gè)section第一個(gè)和最后一個(gè)cell分別添加頂部和底部圓角
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
// 圓角角度
CGFloat radius = 10.f;
// 設(shè)置cell 背景色為透明
cell.backgroundColor = UIColor.clearColor;
// 創(chuàng)建兩個(gè)layer
CAShapeLayer *normalLayer = [[CAShapeLayer alloc] init];
CAShapeLayer *selectLayer = [[CAShapeLayer alloc] init];
// 獲取顯示區(qū)域大小
CGRect bounds = CGRectInset(cell.bounds, kScaleX * 20, 0);
// cell的backgroundView
UIView *normalBgView = [[UIView alloc] initWithFrame:bounds];
// 獲取每組行數(shù)
NSInteger rowNum = [tableView numberOfRowsInSection:indexPath.section];
// 貝塞爾曲線
UIBezierPath *bezierPath = nil;
if (rowNum == 1) {
// 一組只有一行(四個(gè)角全部為圓角)
bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(radius, radius)];
normalBgView.clipsToBounds = NO;
}else {
normalBgView.clipsToBounds = YES;
if (indexPath.row == 0) {
normalBgView.frame = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(-5, 0, 0, 0));
CGRect rect = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(5, 0, 0, 0));
// 每組第一行(添加左上和右上的圓角)
bezierPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight) cornerRadii:CGSizeMake(radius, radius)];
}else if (indexPath.row == rowNum - 1) {
normalBgView.frame = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(0, 0, -5, 0));
CGRect rect = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(0, 0, 5, 0));
// 每組最后一行(添加左下和右下的圓角)
bezierPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:(UIRectCornerBottomLeft|UIRectCornerBottomRight) cornerRadii:CGSizeMake(radius, radius)];
}else {
// 每組不是首位的行不設(shè)置圓角
bezierPath = [UIBezierPath bezierPathWithRect:bounds];
}
}
// 陰影
normalLayer.shadowColor = [UIColor blackColor].CGColor;
normalLayer.shadowOpacity = 0.2;
normalLayer.shadowOffset = CGSizeMake(0, 0);
normalLayer.path = bezierPath.CGPath;
normalLayer.shadowPath = bezierPath.CGPath;
// 把已經(jīng)繪制好的貝塞爾曲線路徑賦值給圖層,然后圖層根據(jù)path進(jìn)行圖像渲染render
normalLayer.path = bezierPath.CGPath;
selectLayer.path = bezierPath.CGPath;
// 設(shè)置填充顏色
normalLayer.fillColor = [UIColor whiteColor].CGColor;
// 添加圖層到nomarBgView中
[normalBgView.layer insertSublayer:normalLayer atIndex:0];
normalBgView.backgroundColor = UIColor.clearColor;
cell.backgroundView = normalBgView;
// 替換cell點(diǎn)擊效果
UIView *selectBgView = [[UIView alloc] initWithFrame:bounds];
selectLayer.fillColor = [UIColor colorWithWhite:0.95 alpha:1.0].CGColor;
[selectBgView.layer insertSublayer:selectLayer atIndex:0];
selectBgView.backgroundColor = UIColor.clearColor;
cell.selectedBackgroundView = selectBgView;
}