分組圓角.gif
這個一直覺得簡單又不知道從哪兒下手的功能,今天有空,找了下資料動手做一做
主要利用UITableViewDelegate
的willDisplayCell
方法結合UIBezierPath
繪制顯示的圓角
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath;
// 圓角角度
CGFloat radius = 10.f;
// 設置cell 背景色為透明
cell.backgroundColor = UIColor.clearColor;
// 創建兩個layer
CAShapeLayer *normalLayer = [[CAShapeLayer alloc] init];
CAShapeLayer *selectLayer = [[CAShapeLayer alloc] init];
// 獲取顯示區域大小
CGRect bounds = CGRectInset(cell.bounds, 10, 0);
// 獲取每組行數
NSInteger rowNum = [tableView numberOfRowsInSection:indexPath.section];
// 貝塞爾曲線
UIBezierPath *bezierPath = nil;
每組考慮只有一行和有多行的情況,若行數為1,則這個cell的每個角都是圓角,否則第一行的左上
和右上
為圓角,最后一行的左下
和右下
為圓角
if (rowNum == 1) {
// 一組只有一行(四個角全部為圓角)
bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds
byRoundingCorners:UIRectCornerAllCorners
cornerRadii:CGSizeMake(radius, radius)];
} else {
if (indexPath.row == 0) {
// 每組第一行(添加左上和右上的圓角)
bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds
byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight)
cornerRadii:CGSizeMake(radius, radius)];
} else if (indexPath.row == rowNum - 1) {
// 每組最后一行(添加左下和右下的圓角)
bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds
byRoundingCorners:(UIRectCornerBottomLeft|UIRectCornerBottomRight)
cornerRadii:CGSizeMake(radius, radius)];
} else {
// 每組不是首位的行不設置圓角
bezierPath = [UIBezierPath bezierPathWithRect:bounds];
}
}
然后將貝塞爾曲線的路徑賦值給圖層,并將圖層添加到view中
// 把已經繪制好的貝塞爾曲線路徑賦值給圖層,然后圖層根據path進行圖像渲染render
normalLayer.path = bezierPath.CGPath;
selectLayer.path = bezierPath.CGPath;
UIView *nomarBgView = [[UIView alloc] initWithFrame:bounds];
// 設置填充顏色
normalLayer.fillColor = [UIColor colorWithWhite:0.95 alpha:1.0].CGColor;
// 添加圖層到nomarBgView中
[nomarBgView.layer insertSublayer:normalLayer atIndex:0];
nomarBgView.backgroundColor = UIColor.clearColor;
cell.backgroundView = nomarBgView;
此時圓角顯示就完成了,但是如果沒有取消cell的點擊效果,還是會出現一個灰色的長方形的形狀,再用上面創建的selectLayer
給cell
添加一個selectedBackgroundView
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;